highscoregames12018 commited on
Commit
2d368c9
·
verified ·
1 Parent(s): cb0d467

Add/update 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 +3 -0
  2. custom_nodes/Civicomfy/download_history.json +0 -0
  3. custom_nodes/ComfyUI-GGUF/.github/workflows/registry.yaml +21 -0
  4. custom_nodes/ComfyUI-GGUF/.gitignore +167 -0
  5. custom_nodes/ComfyUI-GGUF/.tracking +17 -0
  6. custom_nodes/ComfyUI-GGUF/LICENSE +201 -0
  7. custom_nodes/ComfyUI-GGUF/README.md +49 -0
  8. custom_nodes/ComfyUI-GGUF/__init__.py +9 -0
  9. custom_nodes/ComfyUI-GGUF/dequant.py +301 -0
  10. custom_nodes/ComfyUI-GGUF/loader.py +506 -0
  11. custom_nodes/ComfyUI-GGUF/nodes.py +329 -0
  12. custom_nodes/ComfyUI-GGUF/ops.py +281 -0
  13. custom_nodes/ComfyUI-GGUF/pyproject.toml +14 -0
  14. custom_nodes/ComfyUI-GGUF/requirements.txt +5 -0
  15. custom_nodes/ComfyUI-GGUF/tools/README.md +93 -0
  16. custom_nodes/ComfyUI-GGUF/tools/convert.py +365 -0
  17. custom_nodes/ComfyUI-GGUF/tools/fix_5d_tensors.py +82 -0
  18. custom_nodes/ComfyUI-GGUF/tools/fix_lines_ending.py +31 -0
  19. custom_nodes/ComfyUI-GGUF/tools/lcpp.patch +451 -0
  20. custom_nodes/ComfyUI-GGUF/tools/read_tensors.py +21 -0
  21. custom_nodes/ComfyUI_Fill-Nodes/.DS_Store +0 -0
  22. custom_nodes/ComfyUI_Fill-Nodes/.gitattributes +1 -0
  23. custom_nodes/ComfyUI_Fill-Nodes/.github/workflows/publish.yml +21 -0
  24. custom_nodes/ComfyUI_Fill-Nodes/.gitignore +180 -0
  25. custom_nodes/ComfyUI_Fill-Nodes/README.md +539 -0
  26. custom_nodes/ComfyUI_Fill-Nodes/__init__.py +635 -0
  27. custom_nodes/ComfyUI_Fill-Nodes/fonts/Barcode.ttf +0 -0
  28. custom_nodes/ComfyUI_Fill-Nodes/fonts/Circles.ttf +0 -0
  29. custom_nodes/ComfyUI_Fill-Nodes/fonts/Fancy.otf +3 -0
  30. custom_nodes/ComfyUI_Fill-Nodes/fonts/Pattern.otf +3 -0
  31. custom_nodes/ComfyUI_Fill-Nodes/fonts/Square.TTF +0 -0
  32. custom_nodes/ComfyUI_Fill-Nodes/fonts/arial.ttf +3 -0
  33. custom_nodes/ComfyUI_Fill-Nodes/images/.DS_Store +0 -0
  34. custom_nodes/ComfyUI_Fill-Nodes/images/nodes/HF.png +3 -0
  35. custom_nodes/ComfyUI_Fill-Nodes/images/nodes/Patreon.png +3 -0
  36. custom_nodes/ComfyUI_Fill-Nodes/images/nodes/Utility_nodes.png +3 -0
  37. custom_nodes/ComfyUI_Fill-Nodes/images/nodes/VFX_nodes.png +3 -0
  38. custom_nodes/ComfyUI_Fill-Nodes/images/nodes/ai.png +3 -0
  39. custom_nodes/ComfyUI_Fill-Nodes/images/nodes/api.png +3 -0
  40. custom_nodes/ComfyUI_Fill-Nodes/images/nodes/captioning_nodes.png +3 -0
  41. custom_nodes/ComfyUI_Fill-Nodes/images/nodes/clip.png +3 -0
  42. custom_nodes/ComfyUI_Fill-Nodes/images/nodes/discord.png +3 -0
  43. custom_nodes/ComfyUI_Fill-Nodes/images/nodes/experimental.png +3 -0
  44. custom_nodes/ComfyUI_Fill-Nodes/images/nodes/games.png +3 -0
  45. custom_nodes/ComfyUI_Fill-Nodes/images/nodes/googledrive.png +3 -0
  46. custom_nodes/ComfyUI_Fill-Nodes/images/nodes/gpt_nodes.png +3 -0
  47. custom_nodes/ComfyUI_Fill-Nodes/images/nodes/images_nodes.png +3 -0
  48. custom_nodes/ComfyUI_Fill-Nodes/images/nodes/ksampler_nodes.png +3 -0
  49. custom_nodes/ComfyUI_Fill-Nodes/images/nodes/loaders.png +3 -0
  50. custom_nodes/ComfyUI_Fill-Nodes/images/nodes/math.png +3 -0
.gitattributes CHANGED
@@ -56,3 +56,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
56
  custom_nodes/ComfyUI-KJNodes/fonts/FreeMono.ttf filter=lfs diff=lfs merge=lfs -text
57
  custom_nodes/ComfyUI-KJNodes/fonts/FreeMonoBoldOblique.otf filter=lfs diff=lfs merge=lfs -text
58
  custom_nodes/ComfyUI-KJNodes/fonts/TTNorms-Black.otf filter=lfs diff=lfs merge=lfs -text
 
 
 
 
56
  custom_nodes/ComfyUI-KJNodes/fonts/FreeMono.ttf filter=lfs diff=lfs merge=lfs -text
57
  custom_nodes/ComfyUI-KJNodes/fonts/FreeMonoBoldOblique.otf filter=lfs diff=lfs merge=lfs -text
58
  custom_nodes/ComfyUI-KJNodes/fonts/TTNorms-Black.otf filter=lfs diff=lfs merge=lfs -text
59
+ custom_nodes/ComfyUI_Fill-Nodes/fonts/Fancy.otf filter=lfs diff=lfs merge=lfs -text
60
+ custom_nodes/ComfyUI_Fill-Nodes/fonts/Pattern.otf filter=lfs diff=lfs merge=lfs -text
61
+ custom_nodes/ComfyUI_Fill-Nodes/fonts/arial.ttf filter=lfs diff=lfs merge=lfs -text
custom_nodes/Civicomfy/download_history.json CHANGED
The diff for this file is too large to render. See raw diff
 
custom_nodes/ComfyUI-GGUF/.github/workflows/registry.yaml ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: ComfyUI Registry publish
2
+ on:
3
+ workflow_dispatch:
4
+ push:
5
+ branches:
6
+ - stable
7
+ paths:
8
+ - "pyproject.toml"
9
+
10
+ jobs:
11
+ publish-node:
12
+ name: ComfyUI Registry publish
13
+ runs-on: ubuntu-latest
14
+ if: github.event.repository.fork == false
15
+ steps:
16
+ - name: Check out code
17
+ uses: actions/checkout@v4
18
+ - name: Publish Custom Node
19
+ uses: Comfy-Org/publish-node-action@main
20
+ with:
21
+ personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }}
custom_nodes/ComfyUI-GGUF/.gitignore ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.bin
2
+ *.gguf
3
+ *.safetensors
4
+ tools/llama.cpp*
5
+
6
+ # Byte-compiled / optimized / DLL files
7
+ __pycache__/
8
+ *.py[cod]
9
+ *$py.class
10
+
11
+ # C extensions
12
+ *.so
13
+
14
+ # Distribution / packaging
15
+ .Python
16
+ build/
17
+ develop-eggs/
18
+ dist/
19
+ downloads/
20
+ eggs/
21
+ .eggs/
22
+ lib/
23
+ lib64/
24
+ parts/
25
+ sdist/
26
+ var/
27
+ wheels/
28
+ share/python-wheels/
29
+ *.egg-info/
30
+ .installed.cfg
31
+ *.egg
32
+ MANIFEST
33
+
34
+ # PyInstaller
35
+ # Usually these files are written by a python script from a template
36
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
37
+ *.manifest
38
+ *.spec
39
+
40
+ # Installer logs
41
+ pip-log.txt
42
+ pip-delete-this-directory.txt
43
+
44
+ # Unit test / coverage reports
45
+ htmlcov/
46
+ .tox/
47
+ .nox/
48
+ .coverage
49
+ .coverage.*
50
+ .cache
51
+ nosetests.xml
52
+ coverage.xml
53
+ *.cover
54
+ *.py,cover
55
+ .hypothesis/
56
+ .pytest_cache/
57
+ cover/
58
+
59
+ # Translations
60
+ *.mo
61
+ *.pot
62
+
63
+ # Django stuff:
64
+ *.log
65
+ local_settings.py
66
+ db.sqlite3
67
+ db.sqlite3-journal
68
+
69
+ # Flask stuff:
70
+ instance/
71
+ .webassets-cache
72
+
73
+ # Scrapy stuff:
74
+ .scrapy
75
+
76
+ # Sphinx documentation
77
+ docs/_build/
78
+
79
+ # PyBuilder
80
+ .pybuilder/
81
+ target/
82
+
83
+ # Jupyter Notebook
84
+ .ipynb_checkpoints
85
+
86
+ # IPython
87
+ profile_default/
88
+ ipython_config.py
89
+
90
+ # pyenv
91
+ # For a library or package, you might want to ignore these files since the code is
92
+ # intended to run in multiple environments; otherwise, check them in:
93
+ # .python-version
94
+
95
+ # pipenv
96
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
97
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
98
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
99
+ # install all needed dependencies.
100
+ #Pipfile.lock
101
+
102
+ # poetry
103
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
104
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
105
+ # commonly ignored for libraries.
106
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
107
+ #poetry.lock
108
+
109
+ # pdm
110
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
111
+ #pdm.lock
112
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
113
+ # in version control.
114
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
115
+ .pdm.toml
116
+ .pdm-python
117
+ .pdm-build/
118
+
119
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
120
+ __pypackages__/
121
+
122
+ # Celery stuff
123
+ celerybeat-schedule
124
+ celerybeat.pid
125
+
126
+ # SageMath parsed files
127
+ *.sage.py
128
+
129
+ # Environments
130
+ .env
131
+ .venv
132
+ env/
133
+ venv/
134
+ ENV/
135
+ env.bak/
136
+ venv.bak/
137
+
138
+ # Spyder project settings
139
+ .spyderproject
140
+ .spyproject
141
+
142
+ # Rope project settings
143
+ .ropeproject
144
+
145
+ # mkdocs documentation
146
+ /site
147
+
148
+ # mypy
149
+ .mypy_cache/
150
+ .dmypy.json
151
+ dmypy.json
152
+
153
+ # Pyre type checker
154
+ .pyre/
155
+
156
+ # pytype static type analyzer
157
+ .pytype/
158
+
159
+ # Cython debug symbols
160
+ cython_debug/
161
+
162
+ # PyCharm
163
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
164
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
165
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
166
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
167
+ #.idea/
custom_nodes/ComfyUI-GGUF/.tracking ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .github/workflows/registry.yaml
2
+ .gitignore
3
+ LICENSE
4
+ README.md
5
+ __init__.py
6
+ dequant.py
7
+ loader.py
8
+ nodes.py
9
+ ops.py
10
+ pyproject.toml
11
+ requirements.txt
12
+ tools/README.md
13
+ tools/convert.py
14
+ tools/fix_5d_tensors.py
15
+ tools/fix_lines_ending.py
16
+ tools/lcpp.patch
17
+ tools/read_tensors.py
custom_nodes/ComfyUI-GGUF/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-GGUF/README.md ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ComfyUI-GGUF
2
+ GGUF Quantization support for native ComfyUI models
3
+
4
+ This is currently very much WIP. These custom nodes provide support for model files stored in the GGUF format popularized by [llama.cpp](https://github.com/ggerganov/llama.cpp).
5
+
6
+ While quantization wasn't feasible for regular UNET models (conv2d), transformer/DiT models such as flux seem less affected by quantization. This allows running it in much lower bits per weight variable bitrate quants on low-end GPUs. For further VRAM savings, a node to load a quantized version of the T5 text encoder is also included.
7
+
8
+ ![Comfy_Flux1_dev_Q4_0_GGUF_1024](https://github.com/user-attachments/assets/70d16d97-c522-4ef4-9435-633f128644c8)
9
+
10
+ Note: The "Force/Set CLIP Device" is **NOT** part of this node pack. Do not install it if you only have one GPU. Do not set it to cuda:0 then complain about OOM errors if you do not undestand what it is for. There is not need to copy the workflow above, just use your own workflow and replace the stock "Load Diffusion Model" with the "Unet Loader (GGUF)" node.
11
+
12
+ ## Installation
13
+
14
+ > [!IMPORTANT]
15
+ > Make sure your ComfyUI is on a recent-enough version to support custom ops when loading the UNET-only.
16
+
17
+ To install the custom node normally, git clone this repository into your custom nodes folder (`ComfyUI/custom_nodes`) and install the only dependency for inference (`pip install --upgrade gguf`)
18
+
19
+ ```
20
+ git clone https://github.com/city96/ComfyUI-GGUF
21
+ ```
22
+
23
+ To install the custom node on a standalone ComfyUI release, open a CMD inside the "ComfyUI_windows_portable" folder (where your `run_nvidia_gpu.bat` file is) and use the following commands:
24
+
25
+ ```
26
+ git clone https://github.com/city96/ComfyUI-GGUF ComfyUI/custom_nodes/ComfyUI-GGUF
27
+ .\python_embeded\python.exe -s -m pip install -r .\ComfyUI\custom_nodes\ComfyUI-GGUF\requirements.txt
28
+ ```
29
+
30
+ On MacOS sequoia, torch 2.4.1 seems to be required, as 2.6.X nightly versions cause a "M1 buffer is not large enough" error. See [this issue](https://github.com/city96/ComfyUI-GGUF/issues/107) for more information/workarounds.
31
+
32
+ ## Usage
33
+
34
+ Simply use the GGUF Unet loader found under the `bootleg` category. Place the .gguf model files in your `ComfyUI/models/unet` folder.
35
+
36
+ LoRA loading is experimental but it should work with just the built-in LoRA loader node(s).
37
+
38
+ Pre-quantized models:
39
+
40
+ - [flux1-dev GGUF](https://huggingface.co/city96/FLUX.1-dev-gguf)
41
+ - [flux1-schnell GGUF](https://huggingface.co/city96/FLUX.1-schnell-gguf)
42
+ - [stable-diffusion-3.5-large GGUF](https://huggingface.co/city96/stable-diffusion-3.5-large-gguf)
43
+ - [stable-diffusion-3.5-large-turbo GGUF](https://huggingface.co/city96/stable-diffusion-3.5-large-turbo-gguf)
44
+
45
+ Initial support for quantizing T5 has also been added recently, these can be used using the various `*CLIPLoader (gguf)` nodes which can be used inplace of the regular ones. For the CLIP model, use whatever model you were using before for CLIP. The loader can handle both types of files - `gguf` and regular `safetensors`/`bin`.
46
+
47
+ - [t5_v1.1-xxl GGUF](https://huggingface.co/city96/t5-v1_1-xxl-encoder-gguf)
48
+
49
+ See the instructions in the [tools](https://github.com/city96/ComfyUI-GGUF/tree/main/tools) folder for how to create your own quants.
custom_nodes/ComfyUI-GGUF/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # only import if running as a custom node
2
+ try:
3
+ import comfy.utils
4
+ except ImportError:
5
+ pass
6
+ else:
7
+ from .nodes import NODE_CLASS_MAPPINGS
8
+ NODE_DISPLAY_NAME_MAPPINGS = {k:v.TITLE for k,v in NODE_CLASS_MAPPINGS.items()}
9
+ __all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS']
custom_nodes/ComfyUI-GGUF/dequant.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # (c) City96 || Apache-2.0 (apache.org/licenses/LICENSE-2.0)
2
+ import gguf
3
+ import torch
4
+ from tqdm import tqdm
5
+
6
+
7
+ TORCH_COMPATIBLE_QTYPES = (None, gguf.GGMLQuantizationType.F32, gguf.GGMLQuantizationType.F16)
8
+
9
+ def is_torch_compatible(tensor):
10
+ return tensor is None or getattr(tensor, "tensor_type", None) in TORCH_COMPATIBLE_QTYPES
11
+
12
+ def is_quantized(tensor):
13
+ return not is_torch_compatible(tensor)
14
+
15
+ def dequantize_tensor(tensor, dtype=None, dequant_dtype=None):
16
+ qtype = getattr(tensor, "tensor_type", None)
17
+ oshape = getattr(tensor, "tensor_shape", tensor.shape)
18
+
19
+ if qtype in TORCH_COMPATIBLE_QTYPES:
20
+ return tensor.to(dtype)
21
+ elif qtype in dequantize_functions:
22
+ dequant_dtype = dtype if dequant_dtype == "target" else dequant_dtype
23
+ return dequantize(tensor.data, qtype, oshape, dtype=dequant_dtype).to(dtype)
24
+ else:
25
+ # this is incredibly slow
26
+ tqdm.write(f"Falling back to numpy dequant for qtype: {getattr(qtype, 'name', repr(qtype))}")
27
+ new = gguf.quants.dequantize(tensor.cpu().numpy(), qtype)
28
+ return torch.from_numpy(new).to(tensor.device, dtype=dtype)
29
+
30
+ def dequantize(data, qtype, oshape, dtype=None):
31
+ """
32
+ Dequantize tensor back to usable shape/dtype
33
+ """
34
+ block_size, type_size = gguf.GGML_QUANT_SIZES[qtype]
35
+ dequantize_blocks = dequantize_functions[qtype]
36
+
37
+ rows = data.reshape(
38
+ (-1, data.shape[-1])
39
+ ).view(torch.uint8)
40
+
41
+ n_blocks = rows.numel() // type_size
42
+ blocks = rows.reshape((n_blocks, type_size))
43
+ blocks = dequantize_blocks(blocks, block_size, type_size, dtype)
44
+ return blocks.reshape(oshape)
45
+
46
+ def to_uint32(x):
47
+ # no uint32 :(
48
+ x = x.view(torch.uint8).to(torch.int32)
49
+ return (x[:, 0] | x[:, 1] << 8 | x[:, 2] << 16 | x[:, 3] << 24).unsqueeze(1)
50
+
51
+ def to_uint16(x):
52
+ x = x.view(torch.uint8).to(torch.int32)
53
+ return (x[:, 0] | x[:, 1] << 8).unsqueeze(1)
54
+
55
+ def split_block_dims(blocks, *args):
56
+ n_max = blocks.shape[1]
57
+ dims = list(args) + [n_max - sum(args)]
58
+ return torch.split(blocks, dims, dim=1)
59
+
60
+ # Full weights #
61
+ def dequantize_blocks_BF16(blocks, block_size, type_size, dtype=None):
62
+ return (blocks.view(torch.int16).to(torch.int32) << 16).view(torch.float32)
63
+
64
+ # Legacy Quants #
65
+ def dequantize_blocks_Q8_0(blocks, block_size, type_size, dtype=None):
66
+ d, x = split_block_dims(blocks, 2)
67
+ d = d.view(torch.float16).to(dtype)
68
+ x = x.view(torch.int8)
69
+ return (d * x)
70
+
71
+ def dequantize_blocks_Q5_1(blocks, block_size, type_size, dtype=None):
72
+ n_blocks = blocks.shape[0]
73
+
74
+ d, m, qh, qs = split_block_dims(blocks, 2, 2, 4)
75
+ d = d.view(torch.float16).to(dtype)
76
+ m = m.view(torch.float16).to(dtype)
77
+ qh = to_uint32(qh)
78
+
79
+ qh = qh.reshape((n_blocks, 1)) >> torch.arange(32, device=d.device, dtype=torch.int32).reshape(1, 32)
80
+ ql = qs.reshape((n_blocks, -1, 1, block_size // 2)) >> torch.tensor([0, 4], device=d.device, dtype=torch.uint8).reshape(1, 1, 2, 1)
81
+ qh = (qh & 1).to(torch.uint8)
82
+ ql = (ql & 0x0F).reshape((n_blocks, -1))
83
+
84
+ qs = (ql | (qh << 4))
85
+ return (d * qs) + m
86
+
87
+ def dequantize_blocks_Q5_0(blocks, block_size, type_size, dtype=None):
88
+ n_blocks = blocks.shape[0]
89
+
90
+ d, qh, qs = split_block_dims(blocks, 2, 4)
91
+ d = d.view(torch.float16).to(dtype)
92
+ qh = to_uint32(qh)
93
+
94
+ qh = qh.reshape(n_blocks, 1) >> torch.arange(32, device=d.device, dtype=torch.int32).reshape(1, 32)
95
+ ql = qs.reshape(n_blocks, -1, 1, block_size // 2) >> torch.tensor([0, 4], device=d.device, dtype=torch.uint8).reshape(1, 1, 2, 1)
96
+
97
+ qh = (qh & 1).to(torch.uint8)
98
+ ql = (ql & 0x0F).reshape(n_blocks, -1)
99
+
100
+ qs = (ql | (qh << 4)).to(torch.int8) - 16
101
+ return (d * qs)
102
+
103
+ def dequantize_blocks_Q4_1(blocks, block_size, type_size, dtype=None):
104
+ n_blocks = blocks.shape[0]
105
+
106
+ d, m, qs = split_block_dims(blocks, 2, 2)
107
+ d = d.view(torch.float16).to(dtype)
108
+ m = m.view(torch.float16).to(dtype)
109
+
110
+ qs = qs.reshape((n_blocks, -1, 1, block_size // 2)) >> torch.tensor([0, 4], device=d.device, dtype=torch.uint8).reshape(1, 1, 2, 1)
111
+ qs = (qs & 0x0F).reshape(n_blocks, -1)
112
+
113
+ return (d * qs) + m
114
+
115
+ def dequantize_blocks_Q4_0(blocks, block_size, type_size, dtype=None):
116
+ n_blocks = blocks.shape[0]
117
+
118
+ d, qs = split_block_dims(blocks, 2)
119
+ d = d.view(torch.float16).to(dtype)
120
+
121
+ qs = qs.reshape((n_blocks, -1, 1, block_size // 2)) >> torch.tensor([0, 4], device=d.device, dtype=torch.uint8).reshape((1, 1, 2, 1))
122
+ qs = (qs & 0x0F).reshape((n_blocks, -1)).to(torch.int8) - 8
123
+ return (d * qs)
124
+
125
+ # K Quants #
126
+ QK_K = 256
127
+ K_SCALE_SIZE = 12
128
+
129
+ def get_scale_min(scales):
130
+ n_blocks = scales.shape[0]
131
+ scales = scales.view(torch.uint8)
132
+ scales = scales.reshape((n_blocks, 3, 4))
133
+
134
+ d, m, m_d = torch.split(scales, scales.shape[-2] // 3, dim=-2)
135
+
136
+ sc = torch.cat([d & 0x3F, (m_d & 0x0F) | ((d >> 2) & 0x30)], dim=-1)
137
+ min = torch.cat([m & 0x3F, (m_d >> 4) | ((m >> 2) & 0x30)], dim=-1)
138
+
139
+ return (sc.reshape((n_blocks, 8)), min.reshape((n_blocks, 8)))
140
+
141
+ def dequantize_blocks_Q6_K(blocks, block_size, type_size, dtype=None):
142
+ n_blocks = blocks.shape[0]
143
+
144
+ ql, qh, scales, d, = split_block_dims(blocks, QK_K // 2, QK_K // 4, QK_K // 16)
145
+
146
+ scales = scales.view(torch.int8).to(dtype)
147
+ d = d.view(torch.float16).to(dtype)
148
+ d = (d * scales).reshape((n_blocks, QK_K // 16, 1))
149
+
150
+ ql = ql.reshape((n_blocks, -1, 1, 64)) >> torch.tensor([0, 4], device=d.device, dtype=torch.uint8).reshape((1, 1, 2, 1))
151
+ ql = (ql & 0x0F).reshape((n_blocks, -1, 32))
152
+ qh = qh.reshape((n_blocks, -1, 1, 32)) >> torch.tensor([0, 2, 4, 6], device=d.device, dtype=torch.uint8).reshape((1, 1, 4, 1))
153
+ qh = (qh & 0x03).reshape((n_blocks, -1, 32))
154
+ q = (ql | (qh << 4)).to(torch.int8) - 32
155
+ q = q.reshape((n_blocks, QK_K // 16, -1))
156
+
157
+ return (d * q).reshape((n_blocks, QK_K))
158
+
159
+ def dequantize_blocks_Q5_K(blocks, block_size, type_size, dtype=None):
160
+ n_blocks = blocks.shape[0]
161
+
162
+ d, dmin, scales, qh, qs = split_block_dims(blocks, 2, 2, K_SCALE_SIZE, QK_K // 8)
163
+
164
+ d = d.view(torch.float16).to(dtype)
165
+ dmin = dmin.view(torch.float16).to(dtype)
166
+
167
+ sc, m = get_scale_min(scales)
168
+
169
+ d = (d * sc).reshape((n_blocks, -1, 1))
170
+ dm = (dmin * m).reshape((n_blocks, -1, 1))
171
+
172
+ ql = qs.reshape((n_blocks, -1, 1, 32)) >> torch.tensor([0, 4], device=d.device, dtype=torch.uint8).reshape((1, 1, 2, 1))
173
+ qh = qh.reshape((n_blocks, -1, 1, 32)) >> torch.tensor([i for i in range(8)], device=d.device, dtype=torch.uint8).reshape((1, 1, 8, 1))
174
+ ql = (ql & 0x0F).reshape((n_blocks, -1, 32))
175
+ qh = (qh & 0x01).reshape((n_blocks, -1, 32))
176
+ q = (ql | (qh << 4))
177
+
178
+ return (d * q - dm).reshape((n_blocks, QK_K))
179
+
180
+ def dequantize_blocks_Q4_K(blocks, block_size, type_size, dtype=None):
181
+ n_blocks = blocks.shape[0]
182
+
183
+ d, dmin, scales, qs = split_block_dims(blocks, 2, 2, K_SCALE_SIZE)
184
+ d = d.view(torch.float16).to(dtype)
185
+ dmin = dmin.view(torch.float16).to(dtype)
186
+
187
+ sc, m = get_scale_min(scales)
188
+
189
+ d = (d * sc).reshape((n_blocks, -1, 1))
190
+ dm = (dmin * m).reshape((n_blocks, -1, 1))
191
+
192
+ qs = qs.reshape((n_blocks, -1, 1, 32)) >> torch.tensor([0, 4], device=d.device, dtype=torch.uint8).reshape((1, 1, 2, 1))
193
+ qs = (qs & 0x0F).reshape((n_blocks, -1, 32))
194
+
195
+ return (d * qs - dm).reshape((n_blocks, QK_K))
196
+
197
+ def dequantize_blocks_Q3_K(blocks, block_size, type_size, dtype=None):
198
+ n_blocks = blocks.shape[0]
199
+
200
+ hmask, qs, scales, d = split_block_dims(blocks, QK_K // 8, QK_K // 4, 12)
201
+ d = d.view(torch.float16).to(dtype)
202
+
203
+ lscales, hscales = scales[:, :8], scales[:, 8:]
204
+ lscales = lscales.reshape((n_blocks, 1, 8)) >> torch.tensor([0, 4], device=d.device, dtype=torch.uint8).reshape((1, 2, 1))
205
+ lscales = lscales.reshape((n_blocks, 16))
206
+ hscales = hscales.reshape((n_blocks, 1, 4)) >> torch.tensor([0, 2, 4, 6], device=d.device, dtype=torch.uint8).reshape((1, 4, 1))
207
+ hscales = hscales.reshape((n_blocks, 16))
208
+ scales = (lscales & 0x0F) | ((hscales & 0x03) << 4)
209
+ scales = (scales.to(torch.int8) - 32)
210
+
211
+ dl = (d * scales).reshape((n_blocks, 16, 1))
212
+
213
+ ql = qs.reshape((n_blocks, -1, 1, 32)) >> torch.tensor([0, 2, 4, 6], device=d.device, dtype=torch.uint8).reshape((1, 1, 4, 1))
214
+ qh = hmask.reshape(n_blocks, -1, 1, 32) >> torch.tensor([i for i in range(8)], device=d.device, dtype=torch.uint8).reshape((1, 1, 8, 1))
215
+ ql = ql.reshape((n_blocks, 16, QK_K // 16)) & 3
216
+ qh = (qh.reshape((n_blocks, 16, QK_K // 16)) & 1) ^ 1
217
+ q = (ql.to(torch.int8) - (qh << 2).to(torch.int8))
218
+
219
+ return (dl * q).reshape((n_blocks, QK_K))
220
+
221
+ def dequantize_blocks_Q2_K(blocks, block_size, type_size, dtype=None):
222
+ n_blocks = blocks.shape[0]
223
+
224
+ scales, qs, d, dmin = split_block_dims(blocks, QK_K // 16, QK_K // 4, 2)
225
+ d = d.view(torch.float16).to(dtype)
226
+ dmin = dmin.view(torch.float16).to(dtype)
227
+
228
+ # (n_blocks, 16, 1)
229
+ dl = (d * (scales & 0xF)).reshape((n_blocks, QK_K // 16, 1))
230
+ ml = (dmin * (scales >> 4)).reshape((n_blocks, QK_K // 16, 1))
231
+
232
+ shift = torch.tensor([0, 2, 4, 6], device=d.device, dtype=torch.uint8).reshape((1, 1, 4, 1))
233
+
234
+ qs = (qs.reshape((n_blocks, -1, 1, 32)) >> shift) & 3
235
+ qs = qs.reshape((n_blocks, QK_K // 16, 16))
236
+ qs = dl * qs - ml
237
+
238
+ return qs.reshape((n_blocks, -1))
239
+
240
+ # IQ quants
241
+ KVALUES = torch.tensor([-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113], dtype=torch.int8)
242
+
243
+ def dequantize_blocks_IQ4_NL(blocks, block_size, type_size, dtype=None):
244
+ n_blocks = blocks.shape[0]
245
+
246
+ d, qs = split_block_dims(blocks, 2)
247
+ d = d.view(torch.float16).to(dtype)
248
+
249
+ qs = qs.reshape((n_blocks, -1, 1, block_size//2)) >> torch.tensor([0, 4], device=d.device, dtype=torch.uint8).reshape((1, 1, 2, 1))
250
+ qs = (qs & 0x0F).reshape((n_blocks, -1, 1)).to(torch.int64)
251
+
252
+ kvalues = KVALUES.to(qs.device).expand(*qs.shape[:-1], 16)
253
+ qs = torch.gather(kvalues, dim=-1, index=qs).reshape((n_blocks, -1))
254
+ del kvalues # should still be view, but just to be safe
255
+
256
+ return (d * qs)
257
+
258
+ def dequantize_blocks_IQ4_XS(blocks, block_size, type_size, dtype=None):
259
+ n_blocks = blocks.shape[0]
260
+ d, scales_h, scales_l, qs = split_block_dims(blocks, 2, 2, QK_K // 64)
261
+ d = d.view(torch.float16).to(dtype)
262
+ scales_h = to_uint16(scales_h)
263
+
264
+ shift_a = torch.tensor([0, 4], device=d.device, dtype=torch.uint8).reshape((1, 1, 2))
265
+ shift_b = torch.tensor([2 * i for i in range(QK_K // 32)], device=d.device, dtype=torch.uint8).reshape((1, -1, 1))
266
+
267
+ scales_l = scales_l.reshape((n_blocks, -1, 1)) >> shift_a.reshape((1, 1, 2))
268
+ scales_h = scales_h.reshape((n_blocks, -1, 1)) >> shift_b.reshape((1, -1, 1))
269
+
270
+ scales_l = scales_l.reshape((n_blocks, -1)) & 0x0F
271
+ scales_h = scales_h.reshape((n_blocks, -1)).to(torch.uint8) & 0x03
272
+
273
+ scales = (scales_l | (scales_h << 4)).to(torch.int8) - 32
274
+ dl = (d * scales.to(dtype)).reshape((n_blocks, -1, 1))
275
+
276
+ qs = qs.reshape((n_blocks, -1, 1, 16)) >> shift_a.reshape((1, 1, 2, 1))
277
+ qs = qs.reshape((n_blocks, -1, 32, 1)) & 0x0F
278
+
279
+ kvalues = KVALUES.to(qs.device).expand(*qs.shape[:-1], 16)
280
+ qs = torch.gather(kvalues, dim=-1, index=qs.to(torch.int64)).reshape((n_blocks, -1, 32))
281
+ del kvalues # see IQ4_NL
282
+ del shift_a
283
+ del shift_b
284
+
285
+ return (dl * qs).reshape((n_blocks, -1))
286
+
287
+ dequantize_functions = {
288
+ gguf.GGMLQuantizationType.BF16: dequantize_blocks_BF16,
289
+ gguf.GGMLQuantizationType.Q8_0: dequantize_blocks_Q8_0,
290
+ gguf.GGMLQuantizationType.Q5_1: dequantize_blocks_Q5_1,
291
+ gguf.GGMLQuantizationType.Q5_0: dequantize_blocks_Q5_0,
292
+ gguf.GGMLQuantizationType.Q4_1: dequantize_blocks_Q4_1,
293
+ gguf.GGMLQuantizationType.Q4_0: dequantize_blocks_Q4_0,
294
+ gguf.GGMLQuantizationType.Q6_K: dequantize_blocks_Q6_K,
295
+ gguf.GGMLQuantizationType.Q5_K: dequantize_blocks_Q5_K,
296
+ gguf.GGMLQuantizationType.Q4_K: dequantize_blocks_Q4_K,
297
+ gguf.GGMLQuantizationType.Q3_K: dequantize_blocks_Q3_K,
298
+ gguf.GGMLQuantizationType.Q2_K: dequantize_blocks_Q2_K,
299
+ gguf.GGMLQuantizationType.IQ4_NL: dequantize_blocks_IQ4_NL,
300
+ gguf.GGMLQuantizationType.IQ4_XS: dequantize_blocks_IQ4_XS,
301
+ }
custom_nodes/ComfyUI-GGUF/loader.py ADDED
@@ -0,0 +1,506 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # (c) City96 || Apache-2.0 (apache.org/licenses/LICENSE-2.0)
2
+ import warnings
3
+ import logging
4
+ import torch
5
+ import gguf
6
+ import re
7
+ import os
8
+
9
+ from .ops import GGMLTensor
10
+ from .dequant import is_quantized, dequantize_tensor
11
+
12
+ IMG_ARCH_LIST = {"flux", "sd1", "sdxl", "sd3", "aura", "hidream", "cosmos", "ltxv", "hyvid", "wan", "lumina2", "qwen_image"}
13
+ TXT_ARCH_LIST = {"t5", "t5encoder", "llama", "qwen2vl", "qwen3", "qwen3vl", "gemma3"}
14
+ VIS_TYPE_LIST = {"clip-vision", "mmproj"}
15
+
16
+ def get_orig_shape(reader, tensor_name):
17
+ field_key = f"comfy.gguf.orig_shape.{tensor_name}"
18
+ field = reader.get_field(field_key)
19
+ if field is None:
20
+ return None
21
+ # Has original shape metadata, so we try to decode it.
22
+ if len(field.types) != 2 or field.types[0] != gguf.GGUFValueType.ARRAY or field.types[1] != gguf.GGUFValueType.INT32:
23
+ raise TypeError(f"Bad original shape metadata for {field_key}: Expected ARRAY of INT32, got {field.types}")
24
+ return torch.Size(tuple(int(field.parts[part_idx][0]) for part_idx in field.data))
25
+
26
+ def get_field(reader, field_name, field_type):
27
+ field = reader.get_field(field_name)
28
+ if field is None:
29
+ return None
30
+ elif field_type == str:
31
+ # extra check here as this is used for checking arch string
32
+ if len(field.types) != 1 or field.types[0] != gguf.GGUFValueType.STRING:
33
+ raise TypeError(f"Bad type for GGUF {field_name} key: expected string, got {field.types!r}")
34
+ return str(field.parts[field.data[-1]], encoding="utf-8")
35
+ elif field_type in [int, float, bool]:
36
+ return field_type(field.parts[field.data[-1]].item())
37
+ else:
38
+ raise TypeError(f"Unknown field type {field_type}")
39
+
40
+ def get_list_field(reader, field_name, field_type):
41
+ field = reader.get_field(field_name)
42
+ if field is None:
43
+ return None
44
+ elif field_type == str:
45
+ return tuple(str(field.parts[part_idx], encoding="utf-8") for part_idx in field.data)
46
+ elif field_type in [int, float, bool]:
47
+ return tuple(field_type(field.parts[part_idx][0]) for part_idx in field.data)
48
+ else:
49
+ raise TypeError(f"Unknown field type {field_type}")
50
+
51
+ def get_gguf_metadata(reader):
52
+ """Extract all simple metadata fields like safetensors"""
53
+ metadata = {}
54
+ for field_name in reader.fields:
55
+ try:
56
+ field = reader.get_field(field_name)
57
+ if len(field.types) == 1: # Simple scalar fields only
58
+ if field.types[0] == gguf.GGUFValueType.STRING:
59
+ metadata[field_name] = str(field.parts[field.data[-1]], "utf-8")
60
+ elif field.types[0] == gguf.GGUFValueType.INT32:
61
+ metadata[field_name] = int(field.parts[field.data[-1]])
62
+ elif field.types[0] == gguf.GGUFValueType.F32:
63
+ metadata[field_name] = float(field.parts[field.data[-1]])
64
+ elif field.types[0] == gguf.GGUFValueType.BOOL:
65
+ metadata[field_name] = bool(field.parts[field.data[-1]])
66
+ except:
67
+ continue
68
+ return metadata
69
+
70
+ def gguf_sd_loader(path, handle_prefix="model.diffusion_model.", is_text_model=False):
71
+ """
72
+ Read state dict as fake tensors
73
+ """
74
+ reader = gguf.GGUFReader(path)
75
+
76
+ # filter and strip prefix
77
+ has_prefix = False
78
+ if handle_prefix is not None:
79
+ prefix_len = len(handle_prefix)
80
+ tensor_names = set(tensor.name for tensor in reader.tensors)
81
+ has_prefix = any(s.startswith(handle_prefix) for s in tensor_names)
82
+
83
+ tensors = []
84
+ for tensor in reader.tensors:
85
+ sd_key = tensor_name = tensor.name
86
+ if has_prefix:
87
+ if not tensor_name.startswith(handle_prefix):
88
+ continue
89
+ sd_key = tensor_name[prefix_len:]
90
+ tensors.append((sd_key, tensor))
91
+
92
+ # detect and verify architecture
93
+ compat = None
94
+ arch_str = get_field(reader, "general.architecture", str)
95
+ type_str = get_field(reader, "general.type", str)
96
+ if arch_str in [None, "pig", "cow"]:
97
+ if is_text_model:
98
+ raise ValueError(f"This gguf file is incompatible with llama.cpp!\nConsider using safetensors or a compatible gguf file\n({path})")
99
+ compat = "sd.cpp" if arch_str is None else arch_str
100
+ # import here to avoid changes to convert.py breaking regular models
101
+ from .tools.convert import detect_arch
102
+ try:
103
+ arch_str = detect_arch(set(val[0] for val in tensors)).arch
104
+ except Exception as e:
105
+ raise ValueError(f"This model is not currently supported - ({e})")
106
+ elif arch_str not in TXT_ARCH_LIST and is_text_model:
107
+ if type_str not in VIS_TYPE_LIST:
108
+ raise ValueError(f"Unexpected text model architecture type in GGUF file: {arch_str!r}")
109
+ elif arch_str not in IMG_ARCH_LIST and not is_text_model:
110
+ raise ValueError(f"Unexpected architecture type in GGUF file: {arch_str!r}")
111
+
112
+ if compat:
113
+ logging.warning(f"Warning: This gguf model file is loaded in compatibility mode '{compat}' [arch:{arch_str}]")
114
+
115
+ # main loading loop
116
+ state_dict = {}
117
+ qtype_dict = {}
118
+ for sd_key, tensor in tensors:
119
+ tensor_name = tensor.name
120
+ # torch_tensor = torch.from_numpy(tensor.data) # mmap
121
+
122
+ # NOTE: line above replaced with this block to avoid persistent numpy warning about mmap
123
+ with warnings.catch_warnings():
124
+ warnings.filterwarnings("ignore", message="The given NumPy array is not writable")
125
+ torch_tensor = torch.from_numpy(tensor.data) # mmap
126
+
127
+ shape = get_orig_shape(reader, tensor_name)
128
+ if shape is None:
129
+ shape = torch.Size(tuple(int(v) for v in reversed(tensor.shape)))
130
+ # Workaround for stable-diffusion.cpp SDXL detection.
131
+ if compat == "sd.cpp" and arch_str == "sdxl":
132
+ if any([tensor_name.endswith(x) for x in (".proj_in.weight", ".proj_out.weight")]):
133
+ while len(shape) > 2 and shape[-1] == 1:
134
+ shape = shape[:-1]
135
+
136
+ # add to state dict
137
+ if tensor.tensor_type in {gguf.GGMLQuantizationType.F32, gguf.GGMLQuantizationType.F16}:
138
+ torch_tensor = torch_tensor.view(*shape)
139
+ state_dict[sd_key] = GGMLTensor(torch_tensor, tensor_type=tensor.tensor_type, tensor_shape=shape)
140
+
141
+ # 1D tensors shouldn't be quantized, this is a fix for BF16
142
+ if len(shape) <= 1 and tensor.tensor_type == gguf.GGMLQuantizationType.BF16:
143
+ state_dict[sd_key] = dequantize_tensor(state_dict[sd_key], dtype=torch.float32)
144
+
145
+ # keep track of loaded tensor types
146
+ tensor_type_str = getattr(tensor.tensor_type, "name", repr(tensor.tensor_type))
147
+ qtype_dict[tensor_type_str] = qtype_dict.get(tensor_type_str, 0) + 1
148
+
149
+ # print loaded tensor type counts
150
+ logging.info("gguf qtypes: " + ", ".join(f"{k} ({v})" for k, v in qtype_dict.items()))
151
+
152
+ # mark largest tensor for vram estimation
153
+ qsd = {k:v for k,v in state_dict.items() if is_quantized(v)}
154
+ if len(qsd) > 0:
155
+ max_key = max(qsd.keys(), key=lambda k: qsd[k].numel())
156
+ state_dict[max_key].is_largest_weight = True
157
+
158
+ # extra info to return
159
+ extra = {
160
+ "arch_str": arch_str,
161
+ "metadata": get_gguf_metadata(reader)
162
+ }
163
+ return (state_dict, extra)
164
+
165
+ # for remapping llama.cpp -> original key names
166
+ T5_SD_MAP = {
167
+ "enc.": "encoder.",
168
+ ".blk.": ".block.",
169
+ "token_embd": "shared",
170
+ "output_norm": "final_layer_norm",
171
+ "attn_q": "layer.0.SelfAttention.q",
172
+ "attn_k": "layer.0.SelfAttention.k",
173
+ "attn_v": "layer.0.SelfAttention.v",
174
+ "attn_o": "layer.0.SelfAttention.o",
175
+ "attn_norm": "layer.0.layer_norm",
176
+ "attn_rel_b": "layer.0.SelfAttention.relative_attention_bias",
177
+ "ffn_up": "layer.1.DenseReluDense.wi_1",
178
+ "ffn_down": "layer.1.DenseReluDense.wo",
179
+ "ffn_gate": "layer.1.DenseReluDense.wi_0",
180
+ "ffn_norm": "layer.1.layer_norm",
181
+ }
182
+
183
+ LLAMA_SD_MAP = {
184
+ "blk.": "model.layers.",
185
+ "attn_norm": "input_layernorm",
186
+ "attn_q_norm.": "self_attn.q_norm.",
187
+ "attn_k_norm.": "self_attn.k_norm.",
188
+ "attn_v_norm.": "self_attn.v_norm.",
189
+ "attn_q": "self_attn.q_proj",
190
+ "attn_k": "self_attn.k_proj",
191
+ "attn_v": "self_attn.v_proj",
192
+ "attn_output": "self_attn.o_proj",
193
+ "ffn_up": "mlp.up_proj",
194
+ "ffn_down": "mlp.down_proj",
195
+ "ffn_gate": "mlp.gate_proj",
196
+ "ffn_norm": "post_attention_layernorm",
197
+ "token_embd": "model.embed_tokens",
198
+ "output_norm": "model.norm",
199
+ "output.weight": "lm_head.weight",
200
+ }
201
+
202
+ GEMMA3_SD_MAP = LLAMA_SD_MAP.copy()
203
+ GEMMA3_SD_MAP.update({
204
+ "ffn_norm": "pre_feedforward_layernorm",
205
+ "post_ffw_norm": "post_feedforward_layernorm",
206
+ "post_attention_norm": "post_attention_layernorm",
207
+ })
208
+
209
+ CLIP_VISION_SD_MAP = {
210
+ "mm.": "visual.merger.mlp.",
211
+ "v.post_ln.": "visual.merger.ln_q.",
212
+ "v.patch_embd": "visual.patch_embed.proj",
213
+ "v.blk.": "visual.blocks.",
214
+ "ffn_up": "mlp.up_proj",
215
+ "ffn_down": "mlp.down_proj",
216
+ "ffn_gate": "mlp.gate_proj",
217
+ "attn_out.": "attn.proj.",
218
+ "ln1.": "norm1.",
219
+ "ln2.": "norm2.",
220
+ }
221
+
222
+ def sd_map_replace(raw_sd, key_map):
223
+ sd = {}
224
+ for k,v in raw_sd.items():
225
+ for s,d in key_map.items():
226
+ k = k.replace(s,d)
227
+ sd[k] = v
228
+ return sd
229
+
230
+ def llama_permute(raw_sd, n_head, n_head_kv):
231
+ # Reverse version of LlamaModel.permute in llama.cpp convert script
232
+ sd = {}
233
+ permute = lambda x,h: x.reshape(h, x.shape[0] // h // 2, 2, *x.shape[1:]).swapaxes(1, 2).reshape(x.shape)
234
+ for k,v in raw_sd.items():
235
+ if k.endswith(("q_proj.weight", "q_proj.bias")):
236
+ v.data = permute(v.data, n_head)
237
+ if k.endswith(("k_proj.weight", "k_proj.bias")):
238
+ v.data = permute(v.data, n_head_kv)
239
+ sd[k] = v
240
+ return sd
241
+
242
+ def gemma3_norm_corrections(sd):
243
+ # Reverse change from Gemma3Model modify_tensors in llama.cpp convert script
244
+ norm_patterns = [
245
+ "input_layernorm.weight",
246
+ "post_attention_layernorm.weight",
247
+ "pre_feedforward_layernorm.weight",
248
+ "post_feedforward_layernorm.weight",
249
+ "self_attn.q_norm.weight",
250
+ "self_attn.k_norm.weight",
251
+ "model.norm.weight"
252
+ ]
253
+ corrected = 0
254
+ for key in list(sd.keys()):
255
+ if any(p in key for p in norm_patterns):
256
+ if is_quantized(sd[key]):
257
+ sd[key] = dequantize_tensor(sd[key], dtype=torch.float32) - 1.0
258
+ else:
259
+ sd[key] = sd[key].float() - 1.0
260
+ corrected += 1
261
+ #logging.info(f"Gemma3: Applied -1 norm correction to {corrected} tensors")
262
+ return sd
263
+
264
+ def strip_quant_suffix(name):
265
+ pattern = r"[-_]?(?:ud-)?i?q[0-9]_[a-z0-9_\-]{1,8}$"
266
+ match = re.search(pattern, name, re.IGNORECASE)
267
+ if match:
268
+ name = name[:match.start()]
269
+ return name
270
+
271
+ def gguf_mmproj_loader(path):
272
+ # Reverse version of Qwen2VLVisionModel.modify_tensors
273
+ logging.info("Attenpting to find mmproj file for text encoder...")
274
+
275
+ # get name to match w/o quant suffix
276
+ tenc_fname = os.path.basename(path)
277
+ tenc = os.path.splitext(tenc_fname)[0].lower()
278
+ tenc = strip_quant_suffix(tenc)
279
+
280
+ # try and find matching mmproj
281
+ target = []
282
+ root = os.path.dirname(path)
283
+ for fname in os.listdir(root):
284
+ name, ext = os.path.splitext(fname)
285
+ if ext.lower() != ".gguf":
286
+ continue
287
+ if "mmproj" not in name.lower():
288
+ continue
289
+ if tenc in name.lower():
290
+ target.append(fname)
291
+
292
+ if len(target) == 0:
293
+ logging.error(f"Error: Can't find mmproj file for '{tenc_fname}' (matching:'{tenc}')! Qwen-Image-Edit will be broken!")
294
+ return {}
295
+ if len(target) > 1:
296
+ logging.error(f"Ambiguous mmproj for text encoder '{tenc_fname}', will use first match.")
297
+
298
+ logging.info(f"Using mmproj '{target[0]}' for text encoder '{tenc_fname}'.")
299
+ target = os.path.join(root, target[0])
300
+ vsd, _ = gguf_sd_loader(target, is_text_model=True)
301
+
302
+ # concat 4D to 5D
303
+ if "v.patch_embd.weight.1" in vsd:
304
+ w1 = dequantize_tensor(vsd.pop("v.patch_embd.weight"), dtype=torch.float32)
305
+ w2 = dequantize_tensor(vsd.pop("v.patch_embd.weight.1"), dtype=torch.float32)
306
+ vsd["v.patch_embd.weight"] = torch.stack([w1, w2], dim=2)
307
+
308
+ # run main replacement
309
+ vsd = sd_map_replace(vsd, CLIP_VISION_SD_MAP)
310
+
311
+ # handle split Q/K/V
312
+ if "visual.blocks.0.attn_q.weight" in vsd:
313
+ attns = {}
314
+ # filter out attentions + group
315
+ for k,v in vsd.items():
316
+ if any(x in k for x in ["attn_q", "attn_k", "attn_v"]):
317
+ k_attn, k_name = k.rsplit(".attn_", 1)
318
+ k_attn += ".attn.qkv." + k_name.split(".")[-1]
319
+ if k_attn not in attns:
320
+ attns[k_attn] = {}
321
+ attns[k_attn][k_name] = dequantize_tensor(
322
+ v, dtype=(torch.bfloat16 if is_quantized(v) else torch.float16)
323
+ )
324
+
325
+ # recombine
326
+ for k,v in attns.items():
327
+ suffix = k.split(".")[-1]
328
+ vsd[k] = torch.cat([
329
+ v[f"q.{suffix}"],
330
+ v[f"k.{suffix}"],
331
+ v[f"v.{suffix}"],
332
+ ], dim=0)
333
+ del attns
334
+
335
+ return vsd
336
+
337
+ def gguf_tokenizer_loader(path, temb_shape):
338
+ # convert gguf tokenizer to spiece
339
+ logging.info("Attempting to recreate sentencepiece tokenizer from GGUF file metadata...")
340
+ try:
341
+ from sentencepiece import sentencepiece_model_pb2 as model
342
+ except ImportError:
343
+ raise ImportError("Please make sure sentencepiece and protobuf are installed.\npip install sentencepiece protobuf")
344
+ spm = model.ModelProto()
345
+
346
+ reader = gguf.GGUFReader(path)
347
+
348
+ if get_field(reader, "tokenizer.ggml.model", str) == "t5":
349
+ if temb_shape == (256384, 4096): # probably UMT5
350
+ spm.trainer_spec.model_type == 1 # Unigram (do we have a T5 w/ BPE?)
351
+ else:
352
+ raise NotImplementedError("Unknown model, can't set tokenizer!")
353
+ else:
354
+ raise NotImplementedError("Unknown model, can't set tokenizer!")
355
+
356
+ spm.normalizer_spec.add_dummy_prefix = get_field(reader, "tokenizer.ggml.add_space_prefix", bool)
357
+ spm.normalizer_spec.remove_extra_whitespaces = get_field(reader, "tokenizer.ggml.remove_extra_whitespaces", bool)
358
+
359
+ tokens = get_list_field(reader, "tokenizer.ggml.tokens", str)
360
+ scores = get_list_field(reader, "tokenizer.ggml.scores", float)
361
+ toktypes = get_list_field(reader, "tokenizer.ggml.token_type", int)
362
+
363
+ for idx, (token, score, toktype) in enumerate(zip(tokens, scores, toktypes)):
364
+ # # These aren't present in the original?
365
+ # if toktype == 5 and idx >= temb_shape[0]%1000):
366
+ # continue
367
+
368
+ piece = spm.SentencePiece()
369
+ piece.piece = token
370
+ piece.score = score
371
+ piece.type = toktype
372
+ spm.pieces.append(piece)
373
+
374
+ # unsure if any of these are correct
375
+ spm.trainer_spec.byte_fallback = True
376
+ spm.trainer_spec.vocab_size = len(tokens) # split off unused?
377
+ spm.trainer_spec.max_sentence_length = 4096
378
+ spm.trainer_spec.eos_id = get_field(reader, "tokenizer.ggml.eos_token_id", int)
379
+ spm.trainer_spec.pad_id = get_field(reader, "tokenizer.ggml.padding_token_id", int)
380
+
381
+ logging.info(f"Created tokenizer with vocab size of {len(spm.pieces)}")
382
+ del reader
383
+ return torch.ByteTensor(list(spm.SerializeToString()))
384
+
385
+ def gguf_tekken_tokenizer_loader(path, temb_shape):
386
+ # convert ggml (hf) tokenizer metadata to tekken/comfy data
387
+ logging.info("Attempting to recreate tekken tokenizer from GGUF file metadata...")
388
+ import json
389
+ import base64
390
+ from transformers.convert_slow_tokenizer import bytes_to_unicode
391
+
392
+ reader = gguf.GGUFReader(path)
393
+
394
+ model_str = get_field(reader, "tokenizer.ggml.model", str)
395
+ if model_str == "gpt2":
396
+ if temb_shape == (131072, 5120): # probably Mistral
397
+ data = {
398
+ "config": {"num_vocab_tokens": 150000, "default_vocab_size": 131072},
399
+ "vocab": [],
400
+ "special_tokens": [],
401
+ }
402
+ else:
403
+ raise NotImplementedError("Unknown model, can't set tokenizer!")
404
+ else:
405
+ raise NotImplementedError("Unknown model, can't set tokenizer!")
406
+
407
+ tokens = get_list_field(reader, "tokenizer.ggml.tokens", str)
408
+ toktypes = get_list_field(reader, "tokenizer.ggml.token_type", int)
409
+
410
+ decoder = {v: k for k, v in bytes_to_unicode().items()}
411
+ for idx, (token, toktype) in enumerate(zip(tokens, toktypes)):
412
+ if toktype == 3:
413
+ data["special_tokens"].append(
414
+ {'rank': idx, 'token_str': token, 'is_control': True}
415
+ )
416
+ else:
417
+ tok = bytes([decoder[char] for char in token])
418
+ data["vocab"].append({
419
+ "rank": len(data["vocab"]),
420
+ "token_bytes": base64.b64encode(tok).decode("ascii"),
421
+ "token_str": tok.decode("utf-8", errors="replace") # ?
422
+ })
423
+
424
+ logging.info(f"Created tekken tokenizer with vocab size of {len(data['vocab'])} (+{len(data['special_tokens'])})")
425
+ del reader
426
+ return torch.ByteTensor(list(json.dumps(data).encode('utf-8')))
427
+
428
+ def gguf_gemma3_tokenizer_loader(path):
429
+ #TODO: merge into gguf_tokenizer_loader
430
+ logging.info("Attempting to recreate sentencepiece tokenizer from GGUF file metadata...")
431
+ try:
432
+ from sentencepiece import sentencepiece_model_pb2 as model
433
+ except ImportError:
434
+ raise ImportError("Please install sentencepiece and protobuf.\npip install sentencepiece protobuf")
435
+ spm = model.ModelProto()
436
+ reader = gguf.GGUFReader(path)
437
+
438
+ spm.normalizer_spec.name = "identity"
439
+ spm.normalizer_spec.add_dummy_prefix = False
440
+ spm.trainer_spec.model_type = 2
441
+ spm.trainer_spec.input_format = "tsv"
442
+ spm.trainer_spec.byte_fallback = True
443
+ spm.trainer_spec.max_sentence_length = 4192
444
+ spm.trainer_spec.bos_piece = "<bos>"
445
+
446
+ tokens = get_list_field(reader, "tokenizer.ggml.tokens", str)
447
+ scores = get_list_field(reader, "tokenizer.ggml.scores", float)
448
+ toktype = get_list_field(reader, "tokenizer.ggml.token_type", int)
449
+
450
+ if not tokens or not scores or not toktype:
451
+ raise ValueError("Missing tokenizer metadata")
452
+
453
+ for idx in range(len(tokens)):
454
+ piece = spm.SentencePiece()
455
+ piece.piece = tokens[idx]
456
+ if idx == 3: # UNK position
457
+ piece.type = 2 # UNK Token
458
+ piece.score = 0.0 # UNK Score
459
+ else:
460
+ piece.type = toktype[idx]
461
+ piece.score = scores[idx]
462
+ spm.pieces.append(piece)
463
+
464
+ spm.trainer_spec.vocab_size = len(spm.pieces)
465
+ logging.info(f"Created tokenizer with vocab size of {len(spm.pieces)}")
466
+
467
+ del reader
468
+ return torch.ByteTensor(list(spm.SerializeToString()))
469
+
470
+ def gguf_clip_loader(path):
471
+ sd, extra = gguf_sd_loader(path, is_text_model=True)
472
+ arch = extra.get("arch_str", None)
473
+ if arch in {"t5", "t5encoder"}:
474
+ temb_key = "token_embd.weight"
475
+ if temb_key in sd and sd[temb_key].shape == (256384, 4096):
476
+ # non-standard Comfy-Org tokenizer
477
+ sd["spiece_model"] = gguf_tokenizer_loader(path, sd[temb_key].shape)
478
+ # TODO: dequantizing token embed here is janky but otherwise we OOM due to tensor being massive.
479
+ logging.warning(f"Dequantizing {temb_key} to prevent runtime OOM.")
480
+ sd[temb_key] = dequantize_tensor(sd[temb_key], dtype=torch.float16)
481
+ sd = sd_map_replace(sd, T5_SD_MAP)
482
+ elif arch in {"llama", "qwen2vl", "qwen3", "qwen3vl", "gemma3"}:
483
+ # TODO: pass model_options["vocab_size"] to loader somehow
484
+ temb_key = "token_embd.weight"
485
+ if temb_key in sd and sd[temb_key].shape[0] >= (64 * 1024):
486
+ if arch == "llama" and sd[temb_key].shape == (131072, 5120):
487
+ # non-standard Comfy-Org tokenizer
488
+ sd["tekken_model"] = gguf_tekken_tokenizer_loader(path, sd[temb_key].shape)
489
+ elif arch == "gemma3":
490
+ sd["spiece_model"] = gguf_gemma3_tokenizer_loader(path)
491
+ # See note above for T5.
492
+ logging.warning(f"Dequantizing {temb_key} to prevent runtime OOM.")
493
+ sd[temb_key] = dequantize_tensor(sd[temb_key], dtype=torch.float16)
494
+ if arch == "gemma3":
495
+ sd = sd_map_replace(sd, GEMMA3_SD_MAP)
496
+ sd = gemma3_norm_corrections(sd)
497
+ else:
498
+ sd = sd_map_replace(sd, LLAMA_SD_MAP)
499
+ if arch == "llama":
500
+ sd = llama_permute(sd, 32, 8) # L3 / Mistral
501
+ if arch == "qwen2vl":
502
+ vsd = gguf_mmproj_loader(path)
503
+ sd.update(vsd)
504
+ else:
505
+ pass
506
+ return sd
custom_nodes/ComfyUI-GGUF/nodes.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # (c) City96 || Apache-2.0 (apache.org/licenses/LICENSE-2.0)
2
+ import torch
3
+ import logging
4
+ import inspect
5
+ import collections
6
+
7
+ import nodes
8
+ import comfy.sd
9
+ import comfy.lora
10
+ import comfy.float
11
+ import comfy.utils
12
+ import comfy.model_patcher
13
+ import comfy.model_management
14
+ import folder_paths
15
+
16
+ from .ops import GGMLOps, move_patch_to_device
17
+ from .loader import gguf_sd_loader, gguf_clip_loader
18
+ from .dequant import is_quantized, is_torch_compatible
19
+
20
+ def update_folder_names_and_paths(key, targets=[]):
21
+ # check for existing key
22
+ base = folder_paths.folder_names_and_paths.get(key, ([], {}))
23
+ base = base[0] if isinstance(base[0], (list, set, tuple)) else []
24
+ # find base key & add w/ fallback, sanity check + warning
25
+ target = next((x for x in targets if x in folder_paths.folder_names_and_paths), targets[0])
26
+ orig, _ = folder_paths.folder_names_and_paths.get(target, ([], {}))
27
+ folder_paths.folder_names_and_paths[key] = (orig or base, {".gguf"})
28
+ if base and base != orig:
29
+ logging.warning(f"Unknown file list already present on key {key}: {base}")
30
+
31
+ # Add a custom keys for files ending in .gguf
32
+ update_folder_names_and_paths("unet_gguf", ["diffusion_models", "unet"])
33
+ update_folder_names_and_paths("clip_gguf", ["text_encoders", "clip"])
34
+
35
+ class GGUFModelPatcher(comfy.model_patcher.ModelPatcher):
36
+ patch_on_device = False
37
+
38
+ def patch_weight_to_device(self, key, device_to=None, inplace_update=False):
39
+ if key not in self.patches:
40
+ return
41
+ weight = comfy.utils.get_attr(self.model, key)
42
+
43
+ patches = self.patches[key]
44
+ if is_quantized(weight):
45
+ out_weight = weight.to(device_to)
46
+ patches = move_patch_to_device(patches, self.load_device if self.patch_on_device else self.offload_device)
47
+ # TODO: do we ever have legitimate duplicate patches? (i.e. patch on top of patched weight)
48
+ out_weight.patches = [(patches, key)]
49
+ else:
50
+ inplace_update = self.weight_inplace_update or inplace_update
51
+ if key not in self.backup:
52
+ self.backup[key] = collections.namedtuple('Dimension', ['weight', 'inplace_update'])(
53
+ weight.to(device=self.offload_device, copy=inplace_update), inplace_update
54
+ )
55
+
56
+ if device_to is not None:
57
+ temp_weight = comfy.model_management.cast_to_device(weight, device_to, torch.float32, copy=True)
58
+ else:
59
+ temp_weight = weight.to(torch.float32, copy=True)
60
+
61
+ out_weight = comfy.lora.calculate_weight(patches, temp_weight, key)
62
+ out_weight = comfy.float.stochastic_rounding(out_weight, weight.dtype)
63
+
64
+ if inplace_update:
65
+ comfy.utils.copy_to_param(self.model, key, out_weight)
66
+ else:
67
+ comfy.utils.set_attr_param(self.model, key, out_weight)
68
+
69
+ def unpatch_model(self, device_to=None, unpatch_weights=True):
70
+ if unpatch_weights:
71
+ for p in self.model.parameters():
72
+ if is_torch_compatible(p):
73
+ continue
74
+ patches = getattr(p, "patches", [])
75
+ if len(patches) > 0:
76
+ p.patches = []
77
+ # TODO: Find another way to not unload after patches
78
+ return super().unpatch_model(device_to=device_to, unpatch_weights=unpatch_weights)
79
+
80
+
81
+ def pin_weight_to_device(self, key):
82
+ op_key = key.rsplit('.', 1)[0]
83
+ if not self.mmap_released and op_key in self.named_modules_to_munmap:
84
+ # TODO: possible to OOM, find better way to detach
85
+ self.named_modules_to_munmap[op_key].to(self.load_device).to(self.offload_device)
86
+ del self.named_modules_to_munmap[op_key]
87
+ super().pin_weight_to_device(key)
88
+
89
+ mmap_released = False
90
+ named_modules_to_munmap = {}
91
+
92
+ def load(self, *args, force_patch_weights=False, **kwargs):
93
+ if not self.mmap_released:
94
+ self.named_modules_to_munmap = dict(self.model.named_modules())
95
+
96
+ # always call `patch_weight_to_device` even for lowvram
97
+ super().load(*args, force_patch_weights=True, **kwargs)
98
+
99
+ # make sure nothing stays linked to mmap after first load
100
+ if not self.mmap_released:
101
+ linked = []
102
+ if kwargs.get("lowvram_model_memory", 0) > 0:
103
+ for n, m in self.named_modules_to_munmap.items():
104
+ if hasattr(m, "weight"):
105
+ device = getattr(m.weight, "device", None)
106
+ if device == self.offload_device:
107
+ linked.append((n, m))
108
+ continue
109
+ if hasattr(m, "bias"):
110
+ device = getattr(m.bias, "device", None)
111
+ if device == self.offload_device:
112
+ linked.append((n, m))
113
+ continue
114
+ if linked and self.load_device != self.offload_device:
115
+ logging.info(f"Attempting to release mmap ({len(linked)})")
116
+ for n, m in linked:
117
+ # TODO: possible to OOM, find better way to detach
118
+ m.to(self.load_device).to(self.offload_device)
119
+ self.mmap_released = True
120
+ self.named_modules_to_munmap = {}
121
+
122
+ def clone(self, *args, **kwargs):
123
+ src_cls = self.__class__
124
+ self.__class__ = GGUFModelPatcher
125
+ n = super().clone(*args, **kwargs)
126
+ n.__class__ = GGUFModelPatcher
127
+ self.__class__ = src_cls
128
+ # GGUF specific clone values below
129
+ n.patch_on_device = getattr(self, "patch_on_device", False)
130
+ n.mmap_released = getattr(self, "mmap_released", False)
131
+ if src_cls != GGUFModelPatcher:
132
+ n.size = 0 # force recalc
133
+ return n
134
+
135
+ class UnetLoaderGGUF:
136
+ @classmethod
137
+ def INPUT_TYPES(s):
138
+ unet_names = [x for x in folder_paths.get_filename_list("unet_gguf")]
139
+ return {
140
+ "required": {
141
+ "unet_name": (unet_names,),
142
+ }
143
+ }
144
+
145
+ RETURN_TYPES = ("MODEL",)
146
+ FUNCTION = "load_unet"
147
+ CATEGORY = "bootleg"
148
+ TITLE = "Unet Loader (GGUF)"
149
+
150
+ def load_unet(self, unet_name, dequant_dtype=None, patch_dtype=None, patch_on_device=None):
151
+ ops = GGMLOps()
152
+
153
+ if dequant_dtype in ("default", None):
154
+ ops.Linear.dequant_dtype = None
155
+ elif dequant_dtype in ["target"]:
156
+ ops.Linear.dequant_dtype = dequant_dtype
157
+ else:
158
+ ops.Linear.dequant_dtype = getattr(torch, dequant_dtype)
159
+
160
+ if patch_dtype in ("default", None):
161
+ ops.Linear.patch_dtype = None
162
+ elif patch_dtype in ["target"]:
163
+ ops.Linear.patch_dtype = patch_dtype
164
+ else:
165
+ ops.Linear.patch_dtype = getattr(torch, patch_dtype)
166
+
167
+ # init model
168
+ unet_path = folder_paths.get_full_path("unet", unet_name)
169
+ sd, extra = gguf_sd_loader(unet_path)
170
+
171
+ kwargs = {}
172
+ valid_params = inspect.signature(comfy.sd.load_diffusion_model_state_dict).parameters
173
+ if "metadata" in valid_params:
174
+ kwargs["metadata"] = extra.get("metadata", {})
175
+
176
+ model = comfy.sd.load_diffusion_model_state_dict(
177
+ sd, model_options={"custom_operations": ops}, **kwargs,
178
+ )
179
+ if model is None:
180
+ logging.error("ERROR UNSUPPORTED UNET {}".format(unet_path))
181
+ raise RuntimeError("ERROR: Could not detect model type of: {}".format(unet_path))
182
+ model = GGUFModelPatcher.clone(model)
183
+ model.patch_on_device = patch_on_device
184
+ return (model,)
185
+
186
+ class UnetLoaderGGUFAdvanced(UnetLoaderGGUF):
187
+ @classmethod
188
+ def INPUT_TYPES(s):
189
+ unet_names = [x for x in folder_paths.get_filename_list("unet_gguf")]
190
+ return {
191
+ "required": {
192
+ "unet_name": (unet_names,),
193
+ "dequant_dtype": (["default", "target", "float32", "float16", "bfloat16"], {"default": "default"}),
194
+ "patch_dtype": (["default", "target", "float32", "float16", "bfloat16"], {"default": "default"}),
195
+ "patch_on_device": ("BOOLEAN", {"default": False}),
196
+ }
197
+ }
198
+ TITLE = "Unet Loader (GGUF/Advanced)"
199
+
200
+ class CLIPLoaderGGUF:
201
+ @classmethod
202
+ def INPUT_TYPES(s):
203
+ base = nodes.CLIPLoader.INPUT_TYPES()
204
+ return {
205
+ "required": {
206
+ "clip_name": (s.get_filename_list(),),
207
+ "type": base["required"]["type"],
208
+ }
209
+ }
210
+
211
+ RETURN_TYPES = ("CLIP",)
212
+ FUNCTION = "load_clip"
213
+ CATEGORY = "bootleg"
214
+ TITLE = "CLIPLoader (GGUF)"
215
+
216
+ @classmethod
217
+ def get_filename_list(s):
218
+ files = []
219
+ files += folder_paths.get_filename_list("clip")
220
+ files += folder_paths.get_filename_list("clip_gguf")
221
+ return sorted(files)
222
+
223
+ def load_data(self, ckpt_paths):
224
+ clip_data = []
225
+ for p in ckpt_paths:
226
+ if p.endswith(".gguf"):
227
+ sd = gguf_clip_loader(p)
228
+ else:
229
+ sd = comfy.utils.load_torch_file(p, safe_load=True)
230
+ if "scaled_fp8" in sd: # NOTE: Scaled FP8 would require different custom ops, but only one can be active
231
+ raise NotImplementedError(f"Mixing scaled FP8 with GGUF is not supported! Use regular CLIP loader or switch model(s)\n({p})")
232
+ clip_data.append(sd)
233
+ return clip_data
234
+
235
+ def load_patcher(self, clip_paths, clip_type, clip_data):
236
+ clip = comfy.sd.load_text_encoder_state_dicts(
237
+ clip_type = clip_type,
238
+ state_dicts = clip_data,
239
+ model_options = {
240
+ "custom_operations": GGMLOps,
241
+ "initial_device": comfy.model_management.text_encoder_offload_device()
242
+ },
243
+ embedding_directory = folder_paths.get_folder_paths("embeddings"),
244
+ )
245
+ clip.patcher = GGUFModelPatcher.clone(clip.patcher)
246
+ return clip
247
+
248
+ def load_clip(self, clip_name, type="stable_diffusion"):
249
+ clip_path = folder_paths.get_full_path("clip", clip_name)
250
+ clip_type = getattr(comfy.sd.CLIPType, type.upper(), comfy.sd.CLIPType.STABLE_DIFFUSION)
251
+ return (self.load_patcher([clip_path], clip_type, self.load_data([clip_path])),)
252
+
253
+ class DualCLIPLoaderGGUF(CLIPLoaderGGUF):
254
+ @classmethod
255
+ def INPUT_TYPES(s):
256
+ base = nodes.DualCLIPLoader.INPUT_TYPES()
257
+ file_options = (s.get_filename_list(), )
258
+ return {
259
+ "required": {
260
+ "clip_name1": file_options,
261
+ "clip_name2": file_options,
262
+ "type": base["required"]["type"],
263
+ }
264
+ }
265
+
266
+ TITLE = "DualCLIPLoader (GGUF)"
267
+
268
+ def load_clip(self, clip_name1, clip_name2, type):
269
+ clip_path1 = folder_paths.get_full_path("clip", clip_name1)
270
+ clip_path2 = folder_paths.get_full_path("clip", clip_name2)
271
+ clip_paths = (clip_path1, clip_path2)
272
+ clip_type = getattr(comfy.sd.CLIPType, type.upper(), comfy.sd.CLIPType.STABLE_DIFFUSION)
273
+ return (self.load_patcher(clip_paths, clip_type, self.load_data(clip_paths)),)
274
+
275
+ class TripleCLIPLoaderGGUF(CLIPLoaderGGUF):
276
+ @classmethod
277
+ def INPUT_TYPES(s):
278
+ file_options = (s.get_filename_list(), )
279
+ return {
280
+ "required": {
281
+ "clip_name1": file_options,
282
+ "clip_name2": file_options,
283
+ "clip_name3": file_options,
284
+ }
285
+ }
286
+
287
+ TITLE = "TripleCLIPLoader (GGUF)"
288
+
289
+ def load_clip(self, clip_name1, clip_name2, clip_name3, type="sd3"):
290
+ clip_path1 = folder_paths.get_full_path("clip", clip_name1)
291
+ clip_path2 = folder_paths.get_full_path("clip", clip_name2)
292
+ clip_path3 = folder_paths.get_full_path("clip", clip_name3)
293
+ clip_paths = (clip_path1, clip_path2, clip_path3)
294
+ clip_type = getattr(comfy.sd.CLIPType, type.upper(), comfy.sd.CLIPType.STABLE_DIFFUSION)
295
+ return (self.load_patcher(clip_paths, clip_type, self.load_data(clip_paths)),)
296
+
297
+ class QuadrupleCLIPLoaderGGUF(CLIPLoaderGGUF):
298
+ @classmethod
299
+ def INPUT_TYPES(s):
300
+ file_options = (s.get_filename_list(), )
301
+ return {
302
+ "required": {
303
+ "clip_name1": file_options,
304
+ "clip_name2": file_options,
305
+ "clip_name3": file_options,
306
+ "clip_name4": file_options,
307
+ }
308
+ }
309
+
310
+ TITLE = "QuadrupleCLIPLoader (GGUF)"
311
+
312
+ def load_clip(self, clip_name1, clip_name2, clip_name3, clip_name4, type="stable_diffusion"):
313
+ clip_path1 = folder_paths.get_full_path("clip", clip_name1)
314
+ clip_path2 = folder_paths.get_full_path("clip", clip_name2)
315
+ clip_path3 = folder_paths.get_full_path("clip", clip_name3)
316
+ clip_path4 = folder_paths.get_full_path("clip", clip_name4)
317
+ clip_paths = (clip_path1, clip_path2, clip_path3, clip_path4)
318
+ clip_type = getattr(comfy.sd.CLIPType, type.upper(), comfy.sd.CLIPType.STABLE_DIFFUSION)
319
+ return (self.load_patcher(clip_paths, clip_type, self.load_data(clip_paths)),)
320
+
321
+ NODE_CLASS_MAPPINGS = {
322
+ "UnetLoaderGGUF": UnetLoaderGGUF,
323
+ "CLIPLoaderGGUF": CLIPLoaderGGUF,
324
+ "DualCLIPLoaderGGUF": DualCLIPLoaderGGUF,
325
+ "TripleCLIPLoaderGGUF": TripleCLIPLoaderGGUF,
326
+ "QuadrupleCLIPLoaderGGUF": QuadrupleCLIPLoaderGGUF,
327
+ "UnetLoaderGGUFAdvanced": UnetLoaderGGUFAdvanced,
328
+ }
329
+
custom_nodes/ComfyUI-GGUF/ops.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # (c) City96 || Apache-2.0 (apache.org/licenses/LICENSE-2.0)
2
+ import gguf
3
+ import torch
4
+ import logging
5
+
6
+ import comfy.ops
7
+ import comfy.lora
8
+ import comfy.model_management
9
+ from .dequant import dequantize_tensor, is_quantized
10
+
11
+ def chained_hasattr(obj, chained_attr):
12
+ probe = obj
13
+ for attr in chained_attr.split('.'):
14
+ if hasattr(probe, attr):
15
+ probe = getattr(probe, attr)
16
+ else:
17
+ return False
18
+ return True
19
+
20
+ # A bakcward and forward compatible way to get `torch.compiler.disable`.
21
+ def get_torch_compiler_disable_decorator():
22
+ def dummy_decorator(*args, **kwargs):
23
+ def noop(x):
24
+ return x
25
+ return noop
26
+
27
+ from packaging import version
28
+
29
+ if not chained_hasattr(torch, "compiler.disable"):
30
+ logging.info("ComfyUI-GGUF: Torch too old for torch.compile - bypassing")
31
+ return dummy_decorator # torch too old
32
+ elif version.parse(torch.__version__) >= version.parse("2.8"):
33
+ logging.info("ComfyUI-GGUF: Allowing full torch compile")
34
+ return dummy_decorator # torch compile works
35
+ if chained_hasattr(torch, "_dynamo.config.nontraceable_tensor_subclasses"):
36
+ logging.info("ComfyUI-GGUF: Allowing full torch compile (nightly)")
37
+ return dummy_decorator # torch compile works, nightly before 2.8 release
38
+ else:
39
+ logging.info("ComfyUI-GGUF: Partial torch compile only, consider updating pytorch")
40
+ return torch.compiler.disable
41
+
42
+ torch_compiler_disable = get_torch_compiler_disable_decorator()
43
+
44
+ class GGMLTensor(torch.Tensor):
45
+ """
46
+ Main tensor-like class for storing quantized weights
47
+ """
48
+ def __init__(self, *args, tensor_type, tensor_shape, patches=[], **kwargs):
49
+ super().__init__()
50
+ self.tensor_type = tensor_type
51
+ self.tensor_shape = tensor_shape
52
+ self.patches = patches
53
+
54
+ def __new__(cls, *args, tensor_type, tensor_shape, patches=[], **kwargs):
55
+ return super().__new__(cls, *args, **kwargs)
56
+
57
+ def to(self, *args, **kwargs):
58
+ new = super().to(*args, **kwargs)
59
+ new.tensor_type = getattr(self, "tensor_type", None)
60
+ new.tensor_shape = getattr(self, "tensor_shape", new.data.shape)
61
+ new.patches = getattr(self, "patches", []).copy()
62
+ return new
63
+
64
+ def clone(self, *args, **kwargs):
65
+ return self
66
+
67
+ def detach(self, *args, **kwargs):
68
+ return self
69
+
70
+ def copy_(self, *args, **kwargs):
71
+ # fixes .weight.copy_ in comfy/clip_model/CLIPTextModel
72
+ try:
73
+ return super().copy_(*args, **kwargs)
74
+ except Exception as e:
75
+ logging.warning(f"ignoring 'copy_' on tensor: {e}")
76
+
77
+ def new_empty(self, size, *args, **kwargs):
78
+ # Intel Arc fix, ref#50
79
+ new_tensor = super().new_empty(size, *args, **kwargs)
80
+ return GGMLTensor(
81
+ new_tensor,
82
+ tensor_type = getattr(self, "tensor_type", None),
83
+ tensor_shape = size,
84
+ patches = getattr(self, "patches", []).copy()
85
+ )
86
+
87
+ @property
88
+ def shape(self):
89
+ if not hasattr(self, "tensor_shape"):
90
+ self.tensor_shape = self.size()
91
+ return self.tensor_shape
92
+
93
+ class GGMLLayer(torch.nn.Module):
94
+ """
95
+ This (should) be responsible for de-quantizing on the fly
96
+ """
97
+ comfy_cast_weights = True
98
+ dequant_dtype = None
99
+ patch_dtype = None
100
+ largest_layer = False
101
+ torch_compatible_tensor_types = {None, gguf.GGMLQuantizationType.F32, gguf.GGMLQuantizationType.F16}
102
+
103
+ def is_ggml_quantized(self, *, weight=None, bias=None):
104
+ if weight is None:
105
+ weight = self.weight
106
+ if bias is None:
107
+ bias = self.bias
108
+ return is_quantized(weight) or is_quantized(bias)
109
+
110
+ def _load_from_state_dict(self, state_dict, prefix, *args, **kwargs):
111
+ weight, bias = state_dict.get(f"{prefix}weight"), state_dict.get(f"{prefix}bias")
112
+ # NOTE: using modified load for linear due to not initializing on creation, see GGMLOps todo
113
+ if self.is_ggml_quantized(weight=weight, bias=bias) or isinstance(self, torch.nn.Linear):
114
+ return self.ggml_load_from_state_dict(state_dict, prefix, *args, **kwargs)
115
+ # Not strictly required, but fixes embedding shape mismatch. Threshold set in loader.py
116
+ if isinstance(self, torch.nn.Embedding) and self.weight.shape[0] >= (64 * 1024):
117
+ return self.ggml_load_from_state_dict(state_dict, prefix, *args, **kwargs)
118
+ return super()._load_from_state_dict(state_dict, prefix, *args, **kwargs)
119
+
120
+ def ggml_load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs):
121
+ prefix_len = len(prefix)
122
+ for k,v in state_dict.items():
123
+ if k[prefix_len:] == "weight":
124
+ self.weight = torch.nn.Parameter(v, requires_grad=False)
125
+ elif k[prefix_len:] == "bias" and v is not None:
126
+ self.bias = torch.nn.Parameter(v, requires_grad=False)
127
+ else:
128
+ unexpected_keys.append(k)
129
+
130
+ # For Linear layer with missing weight
131
+ if self.weight is None and isinstance(self, torch.nn.Linear):
132
+ v = torch.zeros(self.in_features, self.out_features)
133
+ self.weight = torch.nn.Parameter(v, requires_grad=False)
134
+ missing_keys.append(prefix+"weight")
135
+
136
+ # for vram estimation (TODO: less fragile logic?)
137
+ if getattr(self.weight, "is_largest_weight", False):
138
+ self.largest_layer = True
139
+
140
+ def _save_to_state_dict(self, *args, **kwargs):
141
+ if self.is_ggml_quantized():
142
+ return self.ggml_save_to_state_dict(*args, **kwargs)
143
+ return super()._save_to_state_dict(*args, **kwargs)
144
+
145
+ def ggml_save_to_state_dict(self, destination, prefix, keep_vars):
146
+ # This is a fake state dict for vram estimation
147
+ weight = torch.zeros_like(self.weight, device=torch.device("meta"))
148
+ destination[prefix + "weight"] = weight
149
+ if self.bias is not None:
150
+ bias = torch.zeros_like(self.bias, device=torch.device("meta"))
151
+ destination[prefix + "bias"] = bias
152
+
153
+ # Take into account space required for dequantizing the largest tensor
154
+ if self.largest_layer:
155
+ shape = getattr(self.weight, "tensor_shape", self.weight.shape)
156
+ dtype = self.dequant_dtype if self.dequant_dtype and self.dequant_dtype != "target" else torch.float16
157
+ temp = torch.empty(*shape, device=torch.device("meta"), dtype=dtype)
158
+ destination[prefix + "temp.weight"] = temp
159
+
160
+ return
161
+ # This would return the dequantized state dict
162
+ destination[prefix + "weight"] = self.get_weight(self.weight)
163
+ if bias is not None:
164
+ destination[prefix + "bias"] = self.get_weight(self.bias)
165
+
166
+ def get_weight(self, tensor, dtype):
167
+ if tensor is None:
168
+ return
169
+
170
+ # consolidate and load patches to GPU in async
171
+ patch_list = []
172
+ device = tensor.device
173
+ for patches, key in getattr(tensor, "patches", []):
174
+ patch_list += move_patch_to_device(patches, device)
175
+
176
+ # dequantize tensor while patches load
177
+ weight = dequantize_tensor(tensor, dtype, self.dequant_dtype)
178
+
179
+ # prevent propagating custom tensor class
180
+ if isinstance(weight, GGMLTensor):
181
+ weight = torch.Tensor(weight)
182
+
183
+ # apply patches
184
+ if len(patch_list) > 0:
185
+ if self.patch_dtype is None:
186
+ weight = comfy.lora.calculate_weight(patch_list, weight, key)
187
+ else:
188
+ # for testing, may degrade image quality
189
+ patch_dtype = dtype if self.patch_dtype == "target" else self.patch_dtype
190
+ weight = comfy.lora.calculate_weight(patch_list, weight, key, patch_dtype)
191
+ return weight
192
+
193
+ @torch_compiler_disable()
194
+ def cast_bias_weight(s, input=None, dtype=None, device=None, bias_dtype=None):
195
+ if input is not None:
196
+ if dtype is None:
197
+ dtype = getattr(input, "dtype", torch.float32)
198
+ if bias_dtype is None:
199
+ bias_dtype = dtype
200
+ if device is None:
201
+ device = input.device
202
+
203
+ bias = None
204
+ non_blocking = comfy.model_management.device_supports_non_blocking(device)
205
+ if s.bias is not None:
206
+ bias = s.get_weight(s.bias.to(device), dtype)
207
+ bias = comfy.ops.cast_to(bias, bias_dtype, device, non_blocking=non_blocking, copy=False)
208
+
209
+ weight = s.get_weight(s.weight.to(device), dtype)
210
+ weight = comfy.ops.cast_to(weight, dtype, device, non_blocking=non_blocking, copy=False)
211
+ return weight, bias
212
+
213
+ def forward_comfy_cast_weights(self, input, *args, **kwargs):
214
+ if self.is_ggml_quantized():
215
+ out = self.forward_ggml_cast_weights(input, *args, **kwargs)
216
+ else:
217
+ out = super().forward_comfy_cast_weights(input, *args, **kwargs)
218
+
219
+ # non-ggml forward might still propagate custom tensor class
220
+ if isinstance(out, GGMLTensor):
221
+ out = torch.Tensor(out)
222
+ return out
223
+
224
+ def forward_ggml_cast_weights(self, input):
225
+ raise NotImplementedError
226
+
227
+ class GGMLOps(comfy.ops.manual_cast):
228
+ """
229
+ Dequantize weights on the fly before doing the compute
230
+ """
231
+ class Linear(GGMLLayer, comfy.ops.manual_cast.Linear):
232
+ def __init__(self, in_features, out_features, bias=True, device=None, dtype=None):
233
+ torch.nn.Module.__init__(self)
234
+ # TODO: better workaround for reserved memory spike on windows
235
+ # Issue is with `torch.empty` still reserving the full memory for the layer
236
+ # Windows doesn't over-commit memory so without this 24GB+ of pagefile is used
237
+ self.in_features = in_features
238
+ self.out_features = out_features
239
+ self.weight = None
240
+ self.bias = None
241
+
242
+ def forward_ggml_cast_weights(self, input):
243
+ weight, bias = self.cast_bias_weight(input)
244
+ return torch.nn.functional.linear(input, weight, bias)
245
+
246
+ class Conv2d(GGMLLayer, comfy.ops.manual_cast.Conv2d):
247
+ def forward_ggml_cast_weights(self, input):
248
+ weight, bias = self.cast_bias_weight(input)
249
+ return self._conv_forward(input, weight, bias)
250
+
251
+ class Embedding(GGMLLayer, comfy.ops.manual_cast.Embedding):
252
+ def forward_ggml_cast_weights(self, input, out_dtype=None):
253
+ output_dtype = out_dtype
254
+ if self.weight.dtype == torch.float16 or self.weight.dtype == torch.bfloat16:
255
+ out_dtype = None
256
+ weight, _bias = self.cast_bias_weight(self, device=input.device, dtype=out_dtype)
257
+ return torch.nn.functional.embedding(
258
+ input, weight, self.padding_idx, self.max_norm, self.norm_type, self.scale_grad_by_freq, self.sparse
259
+ ).to(dtype=output_dtype)
260
+
261
+ class LayerNorm(GGMLLayer, comfy.ops.manual_cast.LayerNorm):
262
+ def forward_ggml_cast_weights(self, input):
263
+ if self.weight is None:
264
+ return super().forward_comfy_cast_weights(input)
265
+ weight, bias = self.cast_bias_weight(input)
266
+ return torch.nn.functional.layer_norm(input, self.normalized_shape, weight, bias, self.eps)
267
+
268
+ class GroupNorm(GGMLLayer, comfy.ops.manual_cast.GroupNorm):
269
+ def forward_ggml_cast_weights(self, input):
270
+ weight, bias = self.cast_bias_weight(input)
271
+ return torch.nn.functional.group_norm(input, self.num_groups, weight, bias, self.eps)
272
+
273
+ def move_patch_to_device(item, device):
274
+ if isinstance(item, torch.Tensor):
275
+ return item.to(device, non_blocking=True)
276
+ elif isinstance(item, tuple):
277
+ return tuple(move_patch_to_device(x, device) for x in item)
278
+ elif isinstance(item, list):
279
+ return [move_patch_to_device(x, device) for x in item]
280
+ else:
281
+ return item
custom_nodes/ComfyUI-GGUF/pyproject.toml ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "ComfyUI-GGUF"
3
+ description = "GGUF Quantization support for native ComfyUI models."
4
+ version = "1.1.10" # 2.0.0 = GitHub main, 1.X.X = ComfyUI Registry
5
+ license = { file = "LICENSE" }
6
+ dependencies = ["gguf>=0.13.0", "sentencepiece", "protobuf"]
7
+
8
+ [project.urls]
9
+ Repository = "https://github.com/city96/ComfyUI-GGUF"
10
+
11
+ [tool.comfy]
12
+ PublisherId = "city96"
13
+ DisplayName = "ComfyUI-GGUF"
14
+ Icon = ""
custom_nodes/ComfyUI-GGUF/requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # main
2
+ gguf>=0.13.0
3
+ # optional - tokenizer
4
+ sentencepiece
5
+ protobuf
custom_nodes/ComfyUI-GGUF/tools/README.md ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Converting initial model
2
+
3
+ To convert your initial safetensors/ckpt model to FP16/BF16 GGUF, run the following command:
4
+
5
+ ```
6
+ python convert.py --src E:\models\unet\flux1-dev.safetensors
7
+ ```
8
+ Make sure `gguf>=0.13.0` is installed for this step. Optionally, specify the output gguf file with the `--dst` arg.
9
+
10
+ > [!NOTE]
11
+ > Do not use the diffusers UNET format for flux, it won't work, use the default/reference checkpoint key format. This is due to q/k/v being merged into one qkv key.
12
+ > You can convert it by loading it in ComfyUI and saving it using the built-in "ModelSave" node.
13
+
14
+ > [!WARNING]
15
+ > For hunyuan video/wan 2.1, you will see a warning about 5D tensors. This means the script will save a **non functional** model to disk first, that you can quantize. I recommend saving these in a separate `raw` folder to avoid confusion.
16
+ >
17
+ > After quantization, you will have to run `fix_5d_tensor.py` manually to add back the missing key that was saved by the conversion code.
18
+
19
+ ## Quantizing using custom llama.cpp
20
+
21
+ Depending on your git settings, you may need to run the following script first in order to make sure the patch file is valid. It will convert Windows (CRLF) line endings to Unix (LF) ones.
22
+
23
+ ```
24
+ python fix_lines_ending.py
25
+ ```
26
+
27
+ Git clone llama.cpp into the current folder:
28
+
29
+ ```
30
+ git clone https://github.com/ggerganov/llama.cpp
31
+ ```
32
+
33
+ Check out the correct branch, then apply the custom patch needed to add image model support to the repo you just cloned.
34
+
35
+ ```
36
+ cd llama.cpp
37
+ git checkout tags/b3962
38
+ git apply ..\lcpp.patch
39
+ ```
40
+
41
+ Compile the llama-quantize binary. This example uses cmake, on linux you can just use make.
42
+
43
+ ### Visual Studio 2019, Linux, etc...
44
+
45
+ ```
46
+ mkdir build
47
+ cmake -B build
48
+ cmake --build build --config Debug -j10 --target llama-quantize
49
+ cd ..
50
+ ```
51
+
52
+ ### Visual Studio 2022
53
+
54
+ ```
55
+ mkdir build
56
+ cmake -B build -DCMAKE_CXX_STANDARD=17 -DCMAKE_CXX_STANDARD_REQUIRED=ON -DCMAKE_CXX_FLAGS="-std=c++17"
57
+ ```
58
+
59
+ Edit the `llama.cpp\common\log.cpp` file, inserts two lines after the existing first line:
60
+
61
+ ```
62
+ #include "log.h"
63
+
64
+ #define _SILENCE_CXX23_CHRONO_DEPRECATION_WARNING
65
+ #include <chrono>
66
+ ```
67
+
68
+ Then you can build the project:
69
+ ```
70
+ cmake --build build --config Debug -j10 --target llama-quantize
71
+ cd ..
72
+ ```
73
+
74
+ ### Quantize your model
75
+
76
+
77
+ Now you can use the newly build binary to quantize your model to the desired format:
78
+ ```
79
+ llama.cpp\build\bin\Debug\llama-quantize.exe E:\models\unet\flux1-dev-BF16.gguf E:\models\unet\flux1-dev-Q4_K_S.gguf Q4_K_S
80
+ ```
81
+
82
+ You can extract the patch again with `git diff src\llama.cpp > lcpp.patch` if you wish to change something and contribute back.
83
+
84
+ > [!WARNING]
85
+ > For hunyuan video/wan 2.1, you will have to run `fix_5d_tensor.py` after the quantization step is done.
86
+ >
87
+ > Example usage: `fix_5d_tensors.py --src E:\models\video\raw\wan2.1-t2v-1.3b-Q8_0.gguf --dst E:\models\video\wan2.1-t2v-1.3b-Q8_0.gguf`
88
+ >
89
+ > By default, this also saves a `fix_5d_tensors_[arch].safetensors` file in the `ComfyUI-GGUF/tools` folder, it's recommended to delete this after all models have been converted.
90
+
91
+ > [!NOTE]
92
+ > Do not quantize SDXL / SD1 / other Conv2D heavy models. If you do, make sure to **extract the UNET model first**.
93
+ >This should be obvious, but also don't use the resulting llama-quantize binary with LLMs.
custom_nodes/ComfyUI-GGUF/tools/convert.py ADDED
@@ -0,0 +1,365 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # (c) City96 || Apache-2.0 (apache.org/licenses/LICENSE-2.0)
2
+ import os
3
+ import gguf
4
+ import torch
5
+ import logging
6
+ import argparse
7
+ from tqdm import tqdm
8
+ from safetensors.torch import load_file, save_file
9
+
10
+ QUANTIZATION_THRESHOLD = 1024
11
+ REARRANGE_THRESHOLD = 512
12
+ MAX_TENSOR_NAME_LENGTH = 127
13
+ MAX_TENSOR_DIMS = 4
14
+
15
+ class ModelTemplate:
16
+ arch = "invalid" # string describing architecture
17
+ shape_fix = False # whether to reshape tensors
18
+ keys_detect = [] # list of lists to match in state dict
19
+ keys_banned = [] # list of keys that should mark model as invalid for conversion
20
+ keys_hiprec = [] # list of keys that need to be kept in fp32 for some reason
21
+ keys_ignore = [] # list of strings to ignore keys by when found
22
+
23
+ def handle_nd_tensor(self, key, data):
24
+ raise NotImplementedError(f"Tensor detected that exceeds dims supported by C++ code! ({key} @ {data.shape})")
25
+
26
+ class ModelFlux(ModelTemplate):
27
+ arch = "flux"
28
+ keys_detect = [
29
+ ("transformer_blocks.0.attn.norm_added_k.weight",),
30
+ ("double_blocks.0.img_attn.proj.weight",),
31
+ ]
32
+ keys_banned = ["transformer_blocks.0.attn.norm_added_k.weight",]
33
+
34
+ class ModelSD3(ModelTemplate):
35
+ arch = "sd3"
36
+ keys_detect = [
37
+ ("transformer_blocks.0.attn.add_q_proj.weight",),
38
+ ("joint_blocks.0.x_block.attn.qkv.weight",),
39
+ ]
40
+ keys_banned = ["transformer_blocks.0.attn.add_q_proj.weight",]
41
+
42
+ class ModelAura(ModelTemplate):
43
+ arch = "aura"
44
+ keys_detect = [
45
+ ("double_layers.3.modX.1.weight",),
46
+ ("joint_transformer_blocks.3.ff_context.out_projection.weight",),
47
+ ]
48
+ keys_banned = ["joint_transformer_blocks.3.ff_context.out_projection.weight",]
49
+
50
+ class ModelHiDream(ModelTemplate):
51
+ arch = "hidream"
52
+ keys_detect = [
53
+ (
54
+ "caption_projection.0.linear.weight",
55
+ "double_stream_blocks.0.block.ff_i.shared_experts.w3.weight"
56
+ )
57
+ ]
58
+ keys_hiprec = [
59
+ # nn.parameter, can't load from BF16 ver
60
+ ".ff_i.gate.weight",
61
+ "img_emb.emb_pos"
62
+ ]
63
+
64
+ class CosmosPredict2(ModelTemplate):
65
+ arch = "cosmos"
66
+ keys_detect = [
67
+ (
68
+ "blocks.0.mlp.layer1.weight",
69
+ "blocks.0.adaln_modulation_cross_attn.1.weight",
70
+ )
71
+ ]
72
+ keys_hiprec = ["pos_embedder"]
73
+ keys_ignore = ["_extra_state", "accum_"]
74
+
75
+ class ModelHyVid(ModelTemplate):
76
+ arch = "hyvid"
77
+ keys_detect = [
78
+ (
79
+ "double_blocks.0.img_attn_proj.weight",
80
+ "txt_in.individual_token_refiner.blocks.1.self_attn_qkv.weight",
81
+ )
82
+ ]
83
+
84
+ def handle_nd_tensor(self, key, data):
85
+ # hacky but don't have any better ideas
86
+ path = f"./fix_5d_tensors_{self.arch}.safetensors" # TODO: somehow get a path here??
87
+ if os.path.isfile(path):
88
+ raise RuntimeError(f"5D tensor fix file already exists! {path}")
89
+ fsd = {key: torch.from_numpy(data)}
90
+ tqdm.write(f"5D key found in state dict! Manual fix required! - {key} {data.shape}")
91
+ save_file(fsd, path)
92
+
93
+ class ModelWan(ModelHyVid):
94
+ arch = "wan"
95
+ keys_detect = [
96
+ (
97
+ "blocks.0.self_attn.norm_q.weight",
98
+ "text_embedding.2.weight",
99
+ "head.modulation",
100
+ )
101
+ ]
102
+ keys_hiprec = [
103
+ ".modulation" # nn.parameter, can't load from BF16 ver
104
+ ]
105
+
106
+ class ModelLTXV(ModelTemplate):
107
+ arch = "ltxv"
108
+ keys_detect = [
109
+ (
110
+ "adaln_single.emb.timestep_embedder.linear_2.weight",
111
+ "transformer_blocks.27.scale_shift_table",
112
+ "caption_projection.linear_2.weight",
113
+ )
114
+ ]
115
+ keys_hiprec = [
116
+ "scale_shift_table" # nn.parameter, can't load from BF16 base quant
117
+ ]
118
+
119
+ class ModelSDXL(ModelTemplate):
120
+ arch = "sdxl"
121
+ shape_fix = True
122
+ keys_detect = [
123
+ ("down_blocks.0.downsamplers.0.conv.weight", "add_embedding.linear_1.weight",),
124
+ (
125
+ "input_blocks.3.0.op.weight", "input_blocks.6.0.op.weight",
126
+ "output_blocks.2.2.conv.weight", "output_blocks.5.2.conv.weight",
127
+ ), # Non-diffusers
128
+ ("label_emb.0.0.weight",),
129
+ ]
130
+
131
+ class ModelSD1(ModelTemplate):
132
+ arch = "sd1"
133
+ shape_fix = True
134
+ keys_detect = [
135
+ ("down_blocks.0.downsamplers.0.conv.weight",),
136
+ (
137
+ "input_blocks.3.0.op.weight", "input_blocks.6.0.op.weight", "input_blocks.9.0.op.weight",
138
+ "output_blocks.2.1.conv.weight", "output_blocks.5.2.conv.weight", "output_blocks.8.2.conv.weight"
139
+ ), # Non-diffusers
140
+ ]
141
+
142
+ class ModelLumina2(ModelTemplate):
143
+ arch = "lumina2"
144
+ keys_detect = [
145
+ ("cap_embedder.1.weight", "context_refiner.0.attention.qkv.weight")
146
+ ]
147
+
148
+ arch_list = [ModelFlux, ModelSD3, ModelAura, ModelHiDream, CosmosPredict2,
149
+ ModelLTXV, ModelHyVid, ModelWan, ModelSDXL, ModelSD1, ModelLumina2]
150
+
151
+ def is_model_arch(model, state_dict):
152
+ # check if model is correct
153
+ matched = False
154
+ invalid = False
155
+ for match_list in model.keys_detect:
156
+ if all(key in state_dict for key in match_list):
157
+ matched = True
158
+ invalid = any(key in state_dict for key in model.keys_banned)
159
+ break
160
+ assert not invalid, "Model architecture not allowed for conversion! (i.e. reference VS diffusers format)"
161
+ return matched
162
+
163
+ def detect_arch(state_dict):
164
+ model_arch = None
165
+ for arch in arch_list:
166
+ if is_model_arch(arch, state_dict):
167
+ model_arch = arch()
168
+ break
169
+ assert model_arch is not None, "Unknown model architecture!"
170
+ return model_arch
171
+
172
+ def parse_args():
173
+ parser = argparse.ArgumentParser(description="Generate F16 GGUF files from single UNET")
174
+ parser.add_argument("--src", required=True, help="Source model ckpt file.")
175
+ parser.add_argument("--dst", help="Output unet gguf file.")
176
+ args = parser.parse_args()
177
+
178
+ if not os.path.isfile(args.src):
179
+ parser.error("No input provided!")
180
+
181
+ return args
182
+
183
+ def strip_prefix(state_dict):
184
+ # prefix for mixed state dict
185
+ prefix = None
186
+ for pfx in ["model.diffusion_model.", "model."]:
187
+ if any([x.startswith(pfx) for x in state_dict.keys()]):
188
+ prefix = pfx
189
+ break
190
+
191
+ # prefix for uniform state dict
192
+ if prefix is None:
193
+ for pfx in ["net."]:
194
+ if all([x.startswith(pfx) for x in state_dict.keys()]):
195
+ prefix = pfx
196
+ break
197
+
198
+ # strip prefix if found
199
+ if prefix is not None:
200
+ logging.info(f"State dict prefix found: '{prefix}'")
201
+ sd = {}
202
+ for k, v in state_dict.items():
203
+ if prefix not in k:
204
+ continue
205
+ k = k.replace(prefix, "")
206
+ sd[k] = v
207
+ else:
208
+ logging.debug("State dict has no prefix")
209
+ sd = state_dict
210
+
211
+ return sd
212
+
213
+ def load_state_dict(path):
214
+ if any(path.endswith(x) for x in [".ckpt", ".pt", ".bin", ".pth"]):
215
+ state_dict = torch.load(path, map_location="cpu", weights_only=True)
216
+ for subkey in ["model", "module"]:
217
+ if subkey in state_dict:
218
+ state_dict = state_dict[subkey]
219
+ break
220
+ if len(state_dict) < 20:
221
+ raise RuntimeError(f"pt subkey load failed: {state_dict.keys()}")
222
+ else:
223
+ state_dict = load_file(path)
224
+
225
+ return strip_prefix(state_dict)
226
+
227
+ def handle_tensors(writer, state_dict, model_arch):
228
+ name_lengths = tuple(sorted(
229
+ ((key, len(key)) for key in state_dict.keys()),
230
+ key=lambda item: item[1],
231
+ reverse=True,
232
+ ))
233
+ if not name_lengths:
234
+ return
235
+ max_name_len = name_lengths[0][1]
236
+ if max_name_len > MAX_TENSOR_NAME_LENGTH:
237
+ bad_list = ", ".join(f"{key!r} ({namelen})" for key, namelen in name_lengths if namelen > MAX_TENSOR_NAME_LENGTH)
238
+ raise ValueError(f"Can only handle tensor names up to {MAX_TENSOR_NAME_LENGTH} characters. Tensors exceeding the limit: {bad_list}")
239
+ for key, data in tqdm(state_dict.items()):
240
+ old_dtype = data.dtype
241
+
242
+ if any(x in key for x in model_arch.keys_ignore):
243
+ tqdm.write(f"Filtering ignored key: '{key}'")
244
+ continue
245
+
246
+ if data.dtype == torch.bfloat16:
247
+ data = data.to(torch.float32).numpy()
248
+ # this is so we don't break torch 2.0.X
249
+ elif data.dtype in [getattr(torch, "float8_e4m3fn", "_invalid"), getattr(torch, "float8_e5m2", "_invalid")]:
250
+ data = data.to(torch.float16).numpy()
251
+ else:
252
+ data = data.numpy()
253
+
254
+ n_dims = len(data.shape)
255
+ data_shape = data.shape
256
+ if old_dtype == torch.bfloat16:
257
+ data_qtype = gguf.GGMLQuantizationType.BF16
258
+ # elif old_dtype == torch.float32:
259
+ # data_qtype = gguf.GGMLQuantizationType.F32
260
+ else:
261
+ data_qtype = gguf.GGMLQuantizationType.F16
262
+
263
+ # The max no. of dimensions that can be handled by the quantization code is 4
264
+ if len(data.shape) > MAX_TENSOR_DIMS:
265
+ model_arch.handle_nd_tensor(key, data)
266
+ continue # needs to be added back later
267
+
268
+ # get number of parameters (AKA elements) in this tensor
269
+ n_params = 1
270
+ for dim_size in data_shape:
271
+ n_params *= dim_size
272
+
273
+ if old_dtype in (torch.float32, torch.bfloat16):
274
+ if n_dims == 1:
275
+ # one-dimensional tensors should be kept in F32
276
+ # also speeds up inference due to not dequantizing
277
+ data_qtype = gguf.GGMLQuantizationType.F32
278
+
279
+ elif n_params <= QUANTIZATION_THRESHOLD:
280
+ # very small tensors
281
+ data_qtype = gguf.GGMLQuantizationType.F32
282
+
283
+ elif any(x in key for x in model_arch.keys_hiprec):
284
+ # tensors that require max precision
285
+ data_qtype = gguf.GGMLQuantizationType.F32
286
+
287
+ if (model_arch.shape_fix # NEVER reshape for models such as flux
288
+ and n_dims > 1 # Skip one-dimensional tensors
289
+ and n_params >= REARRANGE_THRESHOLD # Only rearrange tensors meeting the size requirement
290
+ and (n_params / 256).is_integer() # Rearranging only makes sense if total elements is divisible by 256
291
+ and not (data.shape[-1] / 256).is_integer() # Only need to rearrange if the last dimension is not divisible by 256
292
+ ):
293
+ orig_shape = data.shape
294
+ data = data.reshape(n_params // 256, 256)
295
+ writer.add_array(f"comfy.gguf.orig_shape.{key}", tuple(int(dim) for dim in orig_shape))
296
+
297
+ try:
298
+ data = gguf.quants.quantize(data, data_qtype)
299
+ except (AttributeError, gguf.QuantError) as e:
300
+ tqdm.write(f"falling back to F16: {e}")
301
+ data_qtype = gguf.GGMLQuantizationType.F16
302
+ data = gguf.quants.quantize(data, data_qtype)
303
+
304
+ new_name = key # do we need to rename?
305
+
306
+ shape_str = f"{{{', '.join(str(n) for n in reversed(data.shape))}}}"
307
+ tqdm.write(f"{f'%-{max_name_len + 4}s' % f'{new_name}'} {old_dtype} --> {data_qtype.name}, shape = {shape_str}")
308
+
309
+ writer.add_tensor(new_name, data, raw_dtype=data_qtype)
310
+
311
+ def convert_file(path, dst_path=None, interact=True, overwrite=False):
312
+ # load & run model detection logic
313
+ state_dict = load_state_dict(path)
314
+ model_arch = detect_arch(state_dict)
315
+ logging.info(f"* Architecture detected from input: {model_arch.arch}")
316
+
317
+ # detect & set dtype for output file
318
+ dtypes = [x.dtype for x in state_dict.values()]
319
+ dtypes = {x:dtypes.count(x) for x in set(dtypes)}
320
+ main_dtype = max(dtypes, key=dtypes.get)
321
+
322
+ if main_dtype == torch.bfloat16:
323
+ ftype_name = "BF16"
324
+ ftype_gguf = gguf.LlamaFileType.MOSTLY_BF16
325
+ # elif main_dtype == torch.float32:
326
+ # ftype_name = "F32"
327
+ # ftype_gguf = None
328
+ else:
329
+ ftype_name = "F16"
330
+ ftype_gguf = gguf.LlamaFileType.MOSTLY_F16
331
+
332
+ if dst_path is None:
333
+ dst_path = f"{os.path.splitext(path)[0]}-{ftype_name}.gguf"
334
+ elif "{ftype}" in dst_path: # lcpp logic
335
+ dst_path = dst_path.replace("{ftype}", ftype_name)
336
+
337
+ if os.path.isfile(dst_path) and not overwrite:
338
+ if interact:
339
+ input("Output exists enter to continue or ctrl+c to abort!")
340
+ else:
341
+ raise OSError("Output exists and overwriting is disabled!")
342
+
343
+ # handle actual file
344
+ writer = gguf.GGUFWriter(path=None, arch=model_arch.arch)
345
+ writer.add_quantization_version(gguf.GGML_QUANT_VERSION)
346
+ if ftype_gguf is not None:
347
+ writer.add_file_type(ftype_gguf)
348
+
349
+ handle_tensors(writer, state_dict, model_arch)
350
+ writer.write_header_to_file(path=dst_path)
351
+ writer.write_kv_data_to_file()
352
+ writer.write_tensors_to_file(progress=True)
353
+ writer.close()
354
+
355
+ fix = f"./fix_5d_tensors_{model_arch.arch}.safetensors"
356
+ if os.path.isfile(fix):
357
+ logging.warning(f"\n### Warning! Fix file found at '{fix}'")
358
+ logging.warning(" you most likely need to run 'fix_5d_tensors.py' after quantization.")
359
+
360
+ return dst_path, model_arch
361
+
362
+ if __name__ == "__main__":
363
+ args = parse_args()
364
+ convert_file(args.src, args.dst)
365
+
custom_nodes/ComfyUI-GGUF/tools/fix_5d_tensors.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # (c) City96 || Apache-2.0 (apache.org/licenses/LICENSE-2.0)
2
+ import os
3
+ import gguf
4
+ import torch
5
+ import argparse
6
+ from tqdm import tqdm
7
+ from safetensors.torch import load_file
8
+
9
+ def get_args():
10
+ parser = argparse.ArgumentParser()
11
+ parser.add_argument("--src", required=True)
12
+ parser.add_argument("--dst", required=True)
13
+ parser.add_argument("--fix", required=False, help="Defaults to ./fix_5d_tensors_[arch].pt")
14
+ parser.add_argument("--overwrite", action="store_true")
15
+ args = parser.parse_args()
16
+
17
+ if not os.path.isfile(args.src):
18
+ parser.error(f"Invalid source file '{args.src}'")
19
+ if not args.overwrite and os.path.exists(args.dst):
20
+ parser.error(f"Output exists, use '--overwrite' ({args.dst})")
21
+
22
+ return args
23
+
24
+ def get_arch_str(reader):
25
+ field = reader.get_field("general.architecture")
26
+ return str(field.parts[field.data[-1]], encoding="utf-8")
27
+
28
+ def get_file_type(reader):
29
+ field = reader.get_field("general.file_type")
30
+ ft = int(field.parts[field.data[-1]])
31
+ return gguf.LlamaFileType(ft)
32
+
33
+ if __name__ == "__main__":
34
+ args = get_args()
35
+
36
+ # read existing
37
+ reader = gguf.GGUFReader(args.src)
38
+ arch = get_arch_str(reader)
39
+ file_type = get_file_type(reader)
40
+ print(f"Detected arch: '{arch}' (ftype: {str(file_type)})")
41
+
42
+ # prep fix
43
+ if args.fix is None:
44
+ args.fix = f"./fix_5d_tensors_{arch}.safetensors"
45
+
46
+ if not os.path.isfile(args.fix):
47
+ raise OSError(f"No 5D tensor fix file: {args.fix}")
48
+
49
+ sd5d = load_file(args.fix)
50
+ sd5d = {k:v.numpy() for k,v in sd5d.items()}
51
+ print("5D tensors:", sd5d.keys())
52
+
53
+ # prep output
54
+ writer = gguf.GGUFWriter(path=None, arch=arch)
55
+ writer.add_quantization_version(gguf.GGML_QUANT_VERSION)
56
+ writer.add_file_type(file_type)
57
+
58
+ added = []
59
+ def add_extra_key(writer, key, data):
60
+ global added
61
+ data_qtype = gguf.GGMLQuantizationType.F32
62
+ data = gguf.quants.quantize(data, data_qtype)
63
+ tqdm.write(f"Adding key {key} ({data.shape})")
64
+ writer.add_tensor(key, data, raw_dtype=data_qtype)
65
+ added.append(key)
66
+
67
+ # main loop to add missing 5D tensor(s)
68
+ for tensor in tqdm(reader.tensors):
69
+ writer.add_tensor(tensor.name, tensor.data, raw_dtype=tensor.tensor_type)
70
+ key5d = tensor.name.replace(".bias", ".weight")
71
+ if key5d in sd5d.keys():
72
+ add_extra_key(writer, key5d, sd5d[key5d])
73
+
74
+ # brute force for any missed
75
+ for key, data in sd5d.items():
76
+ if key not in added:
77
+ add_extra_key(writer, key, data)
78
+
79
+ writer.write_header_to_file(path=args.dst)
80
+ writer.write_kv_data_to_file()
81
+ writer.write_tensors_to_file(progress=True)
82
+ writer.close()
custom_nodes/ComfyUI-GGUF/tools/fix_lines_ending.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ files = ["lcpp.patch", "lcpp_sd3.patch"]
4
+
5
+ def has_unix_line_endings(file_path):
6
+ try:
7
+ with open(file_path, 'rb') as file:
8
+ content = file.read()
9
+ return b'\r\n' not in content
10
+ except Exception as e:
11
+ print(f"Error checking '{file_path}': {e}")
12
+ return False
13
+
14
+ def convert_to_linux_format(file_path):
15
+ try:
16
+ with open(file_path, 'rb') as file:
17
+ content = file.read().replace(b'\r\n', b'\n')
18
+ with open(file_path, 'wb') as file:
19
+ file.write(content)
20
+ print(f"'{file_path}' converted to Linux line endings (LF).")
21
+ except Exception as e:
22
+ print(f"Error processing '{file_path}': {e}")
23
+
24
+ for file in files:
25
+ if os.path.exists(file):
26
+ if has_unix_line_endings(file):
27
+ print(f"'{file}' already has Unix line endings (LF). No conversion needed.")
28
+ else:
29
+ convert_to_linux_format(file)
30
+ else:
31
+ print(f"File '{file}' does not exist.")
custom_nodes/ComfyUI-GGUF/tools/lcpp.patch ADDED
@@ -0,0 +1,451 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/ggml/include/ggml.h b/ggml/include/ggml.h
2
+ index de3c706f..0267c1fa 100644
3
+ --- a/ggml/include/ggml.h
4
+ +++ b/ggml/include/ggml.h
5
+ @@ -223,7 +223,7 @@
6
+ #define GGML_MAX_OP_PARAMS 64
7
+
8
+ #ifndef GGML_MAX_NAME
9
+ -# define GGML_MAX_NAME 64
10
+ +# define GGML_MAX_NAME 128
11
+ #endif
12
+
13
+ #define GGML_DEFAULT_N_THREADS 4
14
+ @@ -2449,6 +2449,7 @@ extern "C" {
15
+
16
+ // manage tensor info
17
+ GGML_API void gguf_add_tensor(struct gguf_context * ctx, const struct ggml_tensor * tensor);
18
+ + GGML_API void gguf_set_tensor_ndim(struct gguf_context * ctx, const char * name, int n_dim);
19
+ GGML_API void gguf_set_tensor_type(struct gguf_context * ctx, const char * name, enum ggml_type type);
20
+ GGML_API void gguf_set_tensor_data(struct gguf_context * ctx, const char * name, const void * data, size_t size);
21
+
22
+ diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c
23
+ index b16c462f..6d1568f1 100644
24
+ --- a/ggml/src/ggml.c
25
+ +++ b/ggml/src/ggml.c
26
+ @@ -22960,6 +22960,14 @@ void gguf_add_tensor(
27
+ ctx->header.n_tensors++;
28
+ }
29
+
30
+ +void gguf_set_tensor_ndim(struct gguf_context * ctx, const char * name, const int n_dim) {
31
+ + const int idx = gguf_find_tensor(ctx, name);
32
+ + if (idx < 0) {
33
+ + GGML_ABORT("tensor not found");
34
+ + }
35
+ + ctx->infos[idx].n_dims = n_dim;
36
+ +}
37
+ +
38
+ void gguf_set_tensor_type(struct gguf_context * ctx, const char * name, enum ggml_type type) {
39
+ const int idx = gguf_find_tensor(ctx, name);
40
+ if (idx < 0) {
41
+ diff --git a/src/llama.cpp b/src/llama.cpp
42
+ index 24e1f1f0..25db4c69 100644
43
+ --- a/src/llama.cpp
44
+ +++ b/src/llama.cpp
45
+ @@ -205,6 +205,17 @@ enum llm_arch {
46
+ LLM_ARCH_GRANITE,
47
+ LLM_ARCH_GRANITE_MOE,
48
+ LLM_ARCH_CHAMELEON,
49
+ + LLM_ARCH_FLUX,
50
+ + LLM_ARCH_SD1,
51
+ + LLM_ARCH_SDXL,
52
+ + LLM_ARCH_SD3,
53
+ + LLM_ARCH_AURA,
54
+ + LLM_ARCH_LTXV,
55
+ + LLM_ARCH_HYVID,
56
+ + LLM_ARCH_WAN,
57
+ + LLM_ARCH_HIDREAM,
58
+ + LLM_ARCH_COSMOS,
59
+ + LLM_ARCH_LUMINA2,
60
+ LLM_ARCH_UNKNOWN,
61
+ };
62
+
63
+ @@ -258,6 +269,17 @@ static const std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
64
+ { LLM_ARCH_GRANITE, "granite" },
65
+ { LLM_ARCH_GRANITE_MOE, "granitemoe" },
66
+ { LLM_ARCH_CHAMELEON, "chameleon" },
67
+ + { LLM_ARCH_FLUX, "flux" },
68
+ + { LLM_ARCH_SD1, "sd1" },
69
+ + { LLM_ARCH_SDXL, "sdxl" },
70
+ + { LLM_ARCH_SD3, "sd3" },
71
+ + { LLM_ARCH_AURA, "aura" },
72
+ + { LLM_ARCH_LTXV, "ltxv" },
73
+ + { LLM_ARCH_HYVID, "hyvid" },
74
+ + { LLM_ARCH_WAN, "wan" },
75
+ + { LLM_ARCH_HIDREAM, "hidream" },
76
+ + { LLM_ARCH_COSMOS, "cosmos" },
77
+ + { LLM_ARCH_LUMINA2, "lumina2" },
78
+ { LLM_ARCH_UNKNOWN, "(unknown)" },
79
+ };
80
+
81
+ @@ -1531,6 +1553,17 @@ static const std::map<llm_arch, std::map<llm_tensor, const char *>> LLM_TENSOR_N
82
+ { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
83
+ },
84
+ },
85
+ + { LLM_ARCH_FLUX, {}},
86
+ + { LLM_ARCH_SD1, {}},
87
+ + { LLM_ARCH_SDXL, {}},
88
+ + { LLM_ARCH_SD3, {}},
89
+ + { LLM_ARCH_AURA, {}},
90
+ + { LLM_ARCH_LTXV, {}},
91
+ + { LLM_ARCH_HYVID, {}},
92
+ + { LLM_ARCH_WAN, {}},
93
+ + { LLM_ARCH_HIDREAM, {}},
94
+ + { LLM_ARCH_COSMOS, {}},
95
+ + { LLM_ARCH_LUMINA2, {}},
96
+ {
97
+ LLM_ARCH_UNKNOWN,
98
+ {
99
+ @@ -5403,6 +5436,25 @@ static void llm_load_hparams(
100
+ // get general kv
101
+ ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
102
+
103
+ + // Disable LLM metadata for image models
104
+ + switch (model.arch) {
105
+ + case LLM_ARCH_FLUX:
106
+ + case LLM_ARCH_SD1:
107
+ + case LLM_ARCH_SDXL:
108
+ + case LLM_ARCH_SD3:
109
+ + case LLM_ARCH_AURA:
110
+ + case LLM_ARCH_LTXV:
111
+ + case LLM_ARCH_HYVID:
112
+ + case LLM_ARCH_WAN:
113
+ + case LLM_ARCH_HIDREAM:
114
+ + case LLM_ARCH_COSMOS:
115
+ + case LLM_ARCH_LUMINA2:
116
+ + model.ftype = ml.ftype;
117
+ + return;
118
+ + default:
119
+ + break;
120
+ + }
121
+ +
122
+ // get hparams kv
123
+ ml.get_key(LLM_KV_VOCAB_SIZE, hparams.n_vocab, false) || ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
124
+
125
+ @@ -18016,6 +18068,134 @@ static void llama_tensor_dequantize_internal(
126
+ workers.clear();
127
+ }
128
+
129
+ +static ggml_type img_tensor_get_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
130
+ + // Special function for quantizing image model tensors
131
+ + const std::string name = ggml_get_name(tensor);
132
+ + const llm_arch arch = qs.model.arch;
133
+ +
134
+ + // Sanity check
135
+ + if (
136
+ + (name.find("model.diffusion_model.") != std::string::npos) ||
137
+ + (name.find("first_stage_model.") != std::string::npos) ||
138
+ + (name.find("single_transformer_blocks.") != std::string::npos) ||
139
+ + (name.find("joint_transformer_blocks.") != std::string::npos)
140
+ + ) {
141
+ + throw std::runtime_error("Invalid input GGUF file. This is not a supported UNET model");
142
+ + }
143
+ +
144
+ + // Unsupported quant types - exclude all IQ quants for now
145
+ + if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS ||
146
+ + ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ||
147
+ + ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S ||
148
+ + ftype == LLAMA_FTYPE_MOSTLY_IQ1_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL ||
149
+ + ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S ||
150
+ + ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_Q4_0_4_4 ||
151
+ + ftype == LLAMA_FTYPE_MOSTLY_Q4_0_4_8 || ftype == LLAMA_FTYPE_MOSTLY_Q4_0_8_8) {
152
+ + throw std::runtime_error("Invalid quantization type for image model (Not supported)");
153
+ + }
154
+ +
155
+ + if ( // Rules for to_v attention
156
+ + (name.find("attn_v.weight") != std::string::npos) ||
157
+ + (name.find(".to_v.weight") != std::string::npos) ||
158
+ + (name.find(".v.weight") != std::string::npos) ||
159
+ + (name.find(".attn.w1v.weight") != std::string::npos) ||
160
+ + (name.find(".attn.w2v.weight") != std::string::npos) ||
161
+ + (name.find("_attn.v_proj.weight") != std::string::npos)
162
+ + ){
163
+ + if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
164
+ + new_type = GGML_TYPE_Q3_K;
165
+ + }
166
+ + else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
167
+ + new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
168
+ + }
169
+ + else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
170
+ + new_type = GGML_TYPE_Q5_K;
171
+ + }
172
+ + else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) {
173
+ + new_type = GGML_TYPE_Q6_K;
174
+ + }
175
+ + else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) {
176
+ + new_type = GGML_TYPE_Q5_K;
177
+ + }
178
+ + ++qs.i_attention_wv;
179
+ + } else if ( // Rules for fused qkv attention
180
+ + (name.find("attn_qkv.weight") != std::string::npos) ||
181
+ + (name.find("attn.qkv.weight") != std::string::npos) ||
182
+ + (name.find("attention.qkv.weight") != std::string::npos)
183
+ + ) {
184
+ + if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
185
+ + new_type = GGML_TYPE_Q4_K;
186
+ + }
187
+ + else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
188
+ + new_type = GGML_TYPE_Q5_K;
189
+ + }
190
+ + else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) {
191
+ + new_type = GGML_TYPE_Q6_K;
192
+ + }
193
+ + } else if ( // Rules for ffn
194
+ + (name.find("ffn_down") != std::string::npos) ||
195
+ + ((name.find("experts.") != std::string::npos) && (name.find(".w2.weight") != std::string::npos)) ||
196
+ + (name.find(".ffn.2.weight") != std::string::npos) || // is this even the right way around?
197
+ + (name.find(".ff.net.2.weight") != std::string::npos) ||
198
+ + (name.find(".mlp.layer2.weight") != std::string::npos) ||
199
+ + (name.find(".adaln_modulation_mlp.2.weight") != std::string::npos) ||
200
+ + (name.find(".feed_forward.w2.weight") != std::string::npos)
201
+ + ) {
202
+ + // TODO: add back `layer_info` with some model specific logic + logic further down
203
+ + if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
204
+ + new_type = GGML_TYPE_Q4_K;
205
+ + }
206
+ + else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
207
+ + new_type = GGML_TYPE_Q5_K;
208
+ + }
209
+ + else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S) {
210
+ + new_type = GGML_TYPE_Q5_K;
211
+ + }
212
+ + else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
213
+ + new_type = GGML_TYPE_Q6_K;
214
+ + }
215
+ + else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) {
216
+ + new_type = GGML_TYPE_Q6_K;
217
+ + }
218
+ + else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_0) {
219
+ + new_type = GGML_TYPE_Q4_1;
220
+ + }
221
+ + else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_0) {
222
+ + new_type = GGML_TYPE_Q5_1;
223
+ + }
224
+ + ++qs.i_ffn_down;
225
+ + }
226
+ +
227
+ + // Sanity check for row shape
228
+ + bool convert_incompatible_tensor = false;
229
+ + if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
230
+ + new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K) {
231
+ + int nx = tensor->ne[0];
232
+ + int ny = tensor->ne[1];
233
+ + if (nx % QK_K != 0) {
234
+ + LLAMA_LOG_WARN("\n\n%s : tensor cols %d x %d are not divisible by %d, required for %s", __func__, nx, ny, QK_K, ggml_type_name(new_type));
235
+ + convert_incompatible_tensor = true;
236
+ + } else {
237
+ + ++qs.n_k_quantized;
238
+ + }
239
+ + }
240
+ + if (convert_incompatible_tensor) {
241
+ + // TODO: Possibly reenable this in the future
242
+ + // switch (new_type) {
243
+ + // case GGML_TYPE_Q2_K:
244
+ + // case GGML_TYPE_Q3_K:
245
+ + // case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
246
+ + // case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
247
+ + // case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
248
+ + // default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
249
+ + // }
250
+ + new_type = GGML_TYPE_F16;
251
+ + LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
252
+ + ++qs.n_fallback;
253
+ + }
254
+ + return new_type;
255
+ +}
256
+ +
257
+ static ggml_type llama_tensor_get_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
258
+ const std::string name = ggml_get_name(tensor);
259
+
260
+ @@ -18513,7 +18693,9 @@ static void llama_model_quantize_internal(const std::string & fname_inp, const s
261
+ if (llama_model_has_encoder(&model)) {
262
+ n_attn_layer *= 3;
263
+ }
264
+ - GGML_ASSERT((qs.n_attention_wv == n_attn_layer) && "n_attention_wv is unexpected");
265
+ + if (model.arch != LLM_ARCH_HYVID) { // TODO: Check why this fails
266
+ + GGML_ASSERT((qs.n_attention_wv == n_attn_layer) && "n_attention_wv is unexpected");
267
+ + }
268
+ }
269
+
270
+ size_t total_size_org = 0;
271
+ @@ -18547,6 +18729,51 @@ static void llama_model_quantize_internal(const std::string & fname_inp, const s
272
+ ctx_outs[i_split] = gguf_init_empty();
273
+ }
274
+ gguf_add_tensor(ctx_outs[i_split], tensor);
275
+ + // SD3 pos_embed needs special fix as first dim is 1, which gets truncated here
276
+ + if (model.arch == LLM_ARCH_SD3) {
277
+ + const std::string name = ggml_get_name(tensor);
278
+ + if (name == "pos_embed" && tensor->ne[2] == 1) {
279
+ + const int n_dim = 3;
280
+ + gguf_set_tensor_ndim(ctx_outs[i_split], "pos_embed", n_dim);
281
+ + LLAMA_LOG_INFO("\n%s: Correcting pos_embed shape for SD3: [key:%s]\n", __func__, tensor->name);
282
+ + }
283
+ + }
284
+ + // same goes for auraflow
285
+ + if (model.arch == LLM_ARCH_AURA) {
286
+ + const std::string name = ggml_get_name(tensor);
287
+ + if (name == "positional_encoding" && tensor->ne[2] == 1) {
288
+ + const int n_dim = 3;
289
+ + gguf_set_tensor_ndim(ctx_outs[i_split], "positional_encoding", n_dim);
290
+ + LLAMA_LOG_INFO("\n%s: Correcting positional_encoding shape for AuraFlow: [key:%s]\n", __func__, tensor->name);
291
+ + }
292
+ + if (name == "register_tokens" && tensor->ne[2] == 1) {
293
+ + const int n_dim = 3;
294
+ + gguf_set_tensor_ndim(ctx_outs[i_split], "register_tokens", n_dim);
295
+ + LLAMA_LOG_INFO("\n%s: Correcting register_tokens shape for AuraFlow: [key:%s]\n", __func__, tensor->name);
296
+ + }
297
+ + }
298
+ + // conv3d fails due to max dims - unsure what to do here as we never even reach this check
299
+ + if (model.arch == LLM_ARCH_HYVID) {
300
+ + const std::string name = ggml_get_name(tensor);
301
+ + if (name == "img_in.proj.weight" && tensor->ne[5] != 1 ) {
302
+ + throw std::runtime_error("img_in.proj.weight size failed for HyVid");
303
+ + }
304
+ + }
305
+ + // All the modulation layers also have dim1, and I think conv3d fails here too but we segfaul way before that...
306
+ + if (model.arch == LLM_ARCH_WAN) {
307
+ + const std::string name = ggml_get_name(tensor);
308
+ + if (name.find(".modulation") != std::string::npos && tensor->ne[2] == 1) {
309
+ + const int n_dim = 3;
310
+ + gguf_set_tensor_ndim(ctx_outs[i_split], tensor->name, n_dim);
311
+ + LLAMA_LOG_INFO("\n%s: Correcting shape for Wan: [key:%s]\n", __func__, tensor->name);
312
+ + }
313
+ + // FLF2V model only
314
+ + if (name == "img_emb.emb_pos") {
315
+ + const int n_dim = 3;
316
+ + gguf_set_tensor_ndim(ctx_outs[i_split], tensor->name, n_dim);
317
+ + LLAMA_LOG_INFO("\n%s: Correcting shape for Wan FLF2V: [key:%s]\n", __func__, tensor->name);
318
+ + }
319
+ + }
320
+ }
321
+
322
+ // Set split info if needed
323
+ @@ -18647,6 +18874,110 @@ static void llama_model_quantize_internal(const std::string & fname_inp, const s
324
+ // do not quantize relative position bias (T5)
325
+ quantize &= name.find("attn_rel_b.weight") == std::string::npos;
326
+
327
+ + // rules for image models
328
+ + bool image_model = false;
329
+ + if (model.arch == LLM_ARCH_FLUX) {
330
+ + image_model = true;
331
+ + quantize &= name.find("txt_in.") == std::string::npos;
332
+ + quantize &= name.find("img_in.") == std::string::npos;
333
+ + quantize &= name.find("time_in.") == std::string::npos;
334
+ + quantize &= name.find("vector_in.") == std::string::npos;
335
+ + quantize &= name.find("guidance_in.") == std::string::npos;
336
+ + quantize &= name.find("final_layer.") == std::string::npos;
337
+ + }
338
+ + if (model.arch == LLM_ARCH_SD1 || model.arch == LLM_ARCH_SDXL) {
339
+ + image_model = true;
340
+ + quantize &= name.find("class_embedding.") == std::string::npos;
341
+ + quantize &= name.find("time_embedding.") == std::string::npos;
342
+ + quantize &= name.find("add_embedding.") == std::string::npos;
343
+ + quantize &= name.find("time_embed.") == std::string::npos;
344
+ + quantize &= name.find("label_emb.") == std::string::npos;
345
+ + quantize &= name.find("conv_in.") == std::string::npos;
346
+ + quantize &= name.find("conv_out.") == std::string::npos;
347
+ + quantize &= name != "input_blocks.0.0.weight";
348
+ + quantize &= name != "out.2.weight";
349
+ + }
350
+ + if (model.arch == LLM_ARCH_SD3) {
351
+ + image_model = true;
352
+ + quantize &= name.find("final_layer.") == std::string::npos;
353
+ + quantize &= name.find("time_text_embed.") == std::string::npos;
354
+ + quantize &= name.find("context_embedder.") == std::string::npos;
355
+ + quantize &= name.find("t_embedder.") == std::string::npos;
356
+ + quantize &= name.find("y_embedder.") == std::string::npos;
357
+ + quantize &= name.find("x_embedder.") == std::string::npos;
358
+ + quantize &= name != "proj_out.weight";
359
+ + quantize &= name != "pos_embed";
360
+ + }
361
+ + if (model.arch == LLM_ARCH_AURA) {
362
+ + image_model = true;
363
+ + quantize &= name.find("t_embedder.") == std::string::npos;
364
+ + quantize &= name.find("init_x_linear.") == std::string::npos;
365
+ + quantize &= name != "modF.1.weight";
366
+ + quantize &= name != "cond_seq_linear.weight";
367
+ + quantize &= name != "final_linear.weight";
368
+ + quantize &= name != "final_linear.weight";
369
+ + quantize &= name != "positional_encoding";
370
+ + quantize &= name != "register_tokens";
371
+ + }
372
+ + if (model.arch == LLM_ARCH_LTXV) {
373
+ + image_model = true;
374
+ + quantize &= name.find("adaln_single.") == std::string::npos;
375
+ + quantize &= name.find("caption_projection.") == std::string::npos;
376
+ + quantize &= name.find("patchify_proj.") == std::string::npos;
377
+ + quantize &= name.find("proj_out.") == std::string::npos;
378
+ + quantize &= name.find("scale_shift_table") == std::string::npos; // last block too
379
+ + }
380
+ + if (model.arch == LLM_ARCH_HYVID) {
381
+ + image_model = true;
382
+ + quantize &= name.find("txt_in.") == std::string::npos;
383
+ + quantize &= name.find("img_in.") == std::string::npos;
384
+ + quantize &= name.find("time_in.") == std::string::npos;
385
+ + quantize &= name.find("vector_in.") == std::string::npos;
386
+ + quantize &= name.find("guidance_in.") == std::string::npos;
387
+ + quantize &= name.find("final_layer.") == std::string::npos;
388
+ + }
389
+ + if (model.arch == LLM_ARCH_WAN) {
390
+ + image_model = true;
391
+ + quantize &= name.find("modulation.") == std::string::npos;
392
+ + quantize &= name.find("patch_embedding.") == std::string::npos;
393
+ + quantize &= name.find("text_embedding.") == std::string::npos;
394
+ + quantize &= name.find("time_projection.") == std::string::npos;
395
+ + quantize &= name.find("time_embedding.") == std::string::npos;
396
+ + quantize &= name.find("img_emb.") == std::string::npos;
397
+ + quantize &= name.find("head.") == std::string::npos;
398
+ + }
399
+ + if (model.arch == LLM_ARCH_HIDREAM) {
400
+ + image_model = true;
401
+ + quantize &= name.find("p_embedder.") == std::string::npos;
402
+ + quantize &= name.find("t_embedder.") == std::string::npos;
403
+ + quantize &= name.find("x_embedder.") == std::string::npos;
404
+ + quantize &= name.find("final_layer.") == std::string::npos;
405
+ + quantize &= name.find(".ff_i.gate.weight") == std::string::npos;
406
+ + quantize &= name.find("caption_projection.") == std::string::npos;
407
+ + }
408
+ + if (model.arch == LLM_ARCH_COSMOS) {
409
+ + image_model = true;
410
+ + quantize &= name.find("p_embedder.") == std::string::npos;
411
+ + quantize &= name.find("t_embedder.") == std::string::npos;
412
+ + quantize &= name.find("t_embedding_norm.") == std::string::npos;
413
+ + quantize &= name.find("x_embedder.") == std::string::npos;
414
+ + quantize &= name.find("pos_embedder.") == std::string::npos;
415
+ + quantize &= name.find("final_layer.") == std::string::npos;
416
+ + }
417
+ + if (model.arch == LLM_ARCH_LUMINA2) {
418
+ + image_model = true;
419
+ + quantize &= name.find("t_embedder.") == std::string::npos;
420
+ + quantize &= name.find("x_embedder.") == std::string::npos;
421
+ + quantize &= name.find("final_layer.") == std::string::npos;
422
+ + quantize &= name.find("cap_embedder.") == std::string::npos;
423
+ + quantize &= name.find("context_refiner.") == std::string::npos;
424
+ + quantize &= name.find("noise_refiner.") == std::string::npos;
425
+ + }
426
+ + // ignore 3D/4D tensors for image models as the code was never meant to handle these
427
+ + if (image_model) {
428
+ + quantize &= ggml_n_dims(tensor) == 2;
429
+ + }
430
+ +
431
+ enum ggml_type new_type;
432
+ void * new_data;
433
+ size_t new_size;
434
+ @@ -18655,6 +18986,9 @@ static void llama_model_quantize_internal(const std::string & fname_inp, const s
435
+ new_type = default_type;
436
+
437
+ // get more optimal quantization type based on the tensor shape, layer, etc.
438
+ + if (image_model) {
439
+ + new_type = img_tensor_get_type(qs, new_type, tensor, ftype);
440
+ + } else {
441
+ if (!params->pure && ggml_is_quantized(default_type)) {
442
+ new_type = llama_tensor_get_type(qs, new_type, tensor, ftype);
443
+ }
444
+ @@ -18664,6 +18998,7 @@ static void llama_model_quantize_internal(const std::string & fname_inp, const s
445
+ if (params->output_tensor_type < GGML_TYPE_COUNT && strcmp(tensor->name, "output.weight") == 0) {
446
+ new_type = params->output_tensor_type;
447
+ }
448
+ + }
449
+
450
+ // If we've decided to quantize to the same type the tensor is already
451
+ // in then there's nothing to do.
custom_nodes/ComfyUI-GGUF/tools/read_tensors.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+ import os
3
+ import sys
4
+ import gguf
5
+
6
+ def read_tensors(path):
7
+ reader = gguf.GGUFReader(path)
8
+ for tensor in reader.tensors:
9
+ if tensor.tensor_type == gguf.GGMLQuantizationType.F32:
10
+ continue
11
+ print(f"{str(tensor.tensor_type):32}: {tensor.name}")
12
+
13
+ try:
14
+ path = sys.argv[1]
15
+ assert os.path.isfile(path), "Invalid path"
16
+ print(f"input: {path}")
17
+ except Exception as e:
18
+ input(f"failed: {e}")
19
+ else:
20
+ read_tensors(path)
21
+ input()
custom_nodes/ComfyUI_Fill-Nodes/.DS_Store ADDED
Binary file (10.2 kB). View file
 
custom_nodes/ComfyUI_Fill-Nodes/.gitattributes ADDED
@@ -0,0 +1 @@
 
 
1
+ *.sh text eol=lf
custom_nodes/ComfyUI_Fill-Nodes/.github/workflows/publish.yml ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Publish to Comfy registry
2
+ on:
3
+ workflow_dispatch:
4
+ push:
5
+ branches:
6
+ - main
7
+ paths:
8
+ - "pyproject.toml"
9
+
10
+ jobs:
11
+ publish-node:
12
+ name: Publish Custom Node to registry
13
+ runs-on: ubuntu-latest
14
+ steps:
15
+ - name: Check out code
16
+ uses: actions/checkout@v4
17
+ - name: Publish Custom Node
18
+ uses: Comfy-Org/publish-node-action@main
19
+ with:
20
+ ## Add your own personal access token to your Github Repository secrets and reference it here.
21
+ personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }}
custom_nodes/ComfyUI_Fill-Nodes/.gitignore ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.code-workspace
6
+ .vscode/
7
+ config.json
8
+ ignore.txt
9
+ .env
10
+ __pycache__
11
+
12
+ # Cache directory
13
+ cache/
14
+
15
+
16
+ # Byte-compiled / optimized / DLL files
17
+ __pycache__/
18
+
19
+ *$py.class
20
+
21
+ # C extensions
22
+ *.so
23
+
24
+ # Distribution / packaging
25
+ .Python
26
+ build/
27
+ develop-eggs/
28
+ dist/
29
+ downloads/
30
+ eggs/
31
+ .eggs/
32
+ lib/
33
+ lib64/
34
+ parts/
35
+ sdist/
36
+ var/
37
+ wheels/
38
+ share/python-wheels/
39
+ *.egg-info/
40
+ .installed.cfg
41
+ *.egg
42
+ MANIFEST
43
+
44
+ # PyInstaller
45
+ # Usually these files are written by a python script from a template
46
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
47
+ *.manifest
48
+ *.spec
49
+
50
+ # Installer logs
51
+ pip-log.txt
52
+ pip-delete-this-directory.txt
53
+
54
+ # Unit test / coverage reports
55
+ htmlcov/
56
+ .tox/
57
+ .nox/
58
+ .coverage
59
+ .coverage.*
60
+ .cache
61
+ nosetests.xml
62
+ coverage.xml
63
+ *.cover
64
+ #*.py,cover
65
+ .hypothesis/
66
+ .pytest_cache/
67
+ cover/
68
+
69
+ # Translations
70
+ *.mo
71
+ *.pot
72
+
73
+ # Django stuff:
74
+ *.log
75
+ local_settings.py
76
+ db.sqlite3
77
+ db.sqlite3-journal
78
+
79
+ # Flask stuff:
80
+ instance/
81
+ .webassets-cache
82
+
83
+ # Scrapy stuff:
84
+ .scrapy
85
+
86
+ # Sphinx documentation
87
+ docs/_build/
88
+
89
+ # PyBuilder
90
+ .pybuilder/
91
+ target/
92
+
93
+ # Jupyter Notebook
94
+ .ipynb_checkpoints
95
+
96
+ # IPython
97
+ profile_default/
98
+ ipython_config.py
99
+
100
+ # pyenv
101
+ # For a library or package, you might want to ignore these files since the code is
102
+ # intended to run in multiple environments; otherwise, check them in:
103
+ # .python-version
104
+
105
+ # pipenv
106
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
107
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
108
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
109
+ # install all needed dependencies.
110
+ #Pipfile.lock
111
+
112
+ # poetry
113
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
114
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
115
+ # commonly ignored for libraries.
116
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
117
+ #poetry.lock
118
+
119
+ # pdm
120
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
121
+ #pdm.lock
122
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
123
+ # in version control.
124
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
125
+ .pdm.toml
126
+ .pdm-python
127
+ .pdm-build/
128
+
129
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
130
+ __pypackages__/
131
+
132
+ # Celery stuff
133
+ celerybeat-schedule
134
+ celerybeat.pid
135
+
136
+ # SageMath parsed files
137
+ *.sage.py
138
+
139
+ # Environments
140
+ .env
141
+ .venv
142
+ env/
143
+ venv/
144
+ ENV/
145
+ env.bak/
146
+ venv.bak/
147
+
148
+ # Spyder project settings
149
+ .spyderproject
150
+ .spyproject
151
+
152
+ # Rope project settings
153
+ .ropeproject
154
+
155
+ # mkdocs documentation
156
+ /site
157
+
158
+ # mypy
159
+ .mypy_cache/
160
+ .dmypy.json
161
+ dmypy.json
162
+
163
+ # Pyre type checker
164
+ .pyre/
165
+
166
+ # pytype static type analyzer
167
+ .pytype/
168
+
169
+ # Cython debug symbols
170
+ cython_debug/
171
+
172
+ # PyCharm
173
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
174
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
175
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
176
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
177
+ .idea/
178
+
179
+ # Claude Code folder
180
+ .claude/
custom_nodes/ComfyUI_Fill-Nodes/README.md ADDED
@@ -0,0 +1,539 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🏵️ Fill-Nodes
2
+
3
+ If you enjoy this project, consider supporting me on Patreon!
4
+ <p align="left">
5
+ <a href="https://www.patreon.com/c/Machinedelusions">
6
+ <img src="images\\nodes\\Patreon.png" width="150px" alt="Patreon">
7
+ </a>
8
+ </p>
9
+
10
+ Fill-Nodes is a versatile collection of custom nodes for ComfyUI that extends functionality across multiple domains. Features include advanced image processing, visual effects generation, comprehensive file handling (PDF creation/extraction, Google Drive integration), AI model interfaces (GPT, DALL-E, Hugging Face, Runway, Gemini, Fal.ai, and more), utility nodes for workflow enhancement, audio-reactive visual effects, and specialized tools for video processing, captioning, and batch operations. The pack provides both practical workflow solutions and creative tools within a unified node collection.
11
+
12
+ ## 🔍 Table of Contents
13
+
14
+ <table>
15
+ <tr>
16
+ <td valign="top">
17
+ <ul>
18
+ <li><a href="#image-nodes">🖼️ Image Nodes</a></li>
19
+ <li><a href="#captioning-nodes">📝 Captioning Nodes</a></li>
20
+ <li><a href="#vfx-nodes">✨ VFX Nodes</a></li>
21
+ <li><a href="#utility-nodes">🛠️ Utility Nodes</a></li>
22
+ <li><a href="#ksamplers-nodes">🎲 KSamplers Nodes</a></li>
23
+ <li><a href="#pdf-nodes">📄 PDF Nodes</a></li>
24
+ <li><a href="#gpt-nodes">🤖 GPT Nodes</a></li>
25
+ </ul>
26
+ </td>
27
+ <td valign="top">
28
+ <ul>
29
+ <li><a href="#ai-nodes">🧠 AI Nodes</a></li>
30
+ <li><a href="#audio-nodes">🔊 Audio Nodes</a></li>
31
+ <li><a href="#experimental-nodes">🧪 Experimental Nodes</a></li>
32
+ <li><a href="#prompting-nodes">💬 Prompting Nodes</a></li>
33
+ <li><a href="#file-operation-nodes">📂 File Operation Nodes</a></li>
34
+ <li><a href="#google-drive-nodes">☁️ Google Drive Nodes</a></li>
35
+ <li><a href="#api-tool-nodes">🔌 API Tool Nodes</a></li>
36
+ </ul>
37
+ </td>
38
+ <td valign="top">
39
+ <ul>
40
+ <li><a href="#hugging-face-nodes">🤗 Hugging Face Nodes</a></li>
41
+ <li><a href="#loader-nodes">⏬ Loader Nodes</a></li>
42
+ <li><a href="#discord-nodes">💬 Discord Nodes</a></li>
43
+ <li><a href="#work-in-progress-nodes">🚧 Work-in-Progress Nodes</a></li>
44
+ <li><a href="#game-nodes">🎮 Game Nodes</a></li>
45
+ <li><a href="#video-nodes">🎬 Video Nodes</a></li>
46
+ </ul>
47
+ </td>
48
+ </tr>
49
+ </table>
50
+
51
+ ---
52
+
53
+ <details>
54
+ <summary><h2 id="-image-nodes">🖼️ Image Nodes</h2></summary>
55
+
56
+ > *Nodes for manipulating, analyzing, and working with images.*
57
+
58
+ | Node | Description |
59
+ |------|-------------|
60
+ | `FL_AnimeLineExtractor` | Extracts line art from images using OpenCV's adaptive thresholding and morphological operations. Provides controls for line threshold, line width, detail level, noise reduction via Gaussian blur, and optional output inversion for white backgrounds. |
61
+ | `FL_ApplyMask` | Applies a mask to an image's alpha channel by adding or modifying the alpha channel based on the provided mask. Automatically handles dimension mismatches between image and mask through interpolation and supports batch processing. |
62
+ | `FL_BlackFrameReject` | Filters out images from a batch based on black pixel percentage using configurable threshold and black level detection. Supports multiple detection methods (luminance, average, RGB, all channels) and optional inversion logic, returning filtered images with count statistics. |
63
+ | `FL_ImageAddNoise` | Adds random Gaussian noise to images with controllable strength (0.0-1.0) and seed for reproducible results. Uses torch.randn to generate noise and clips output to valid 0.0-1.0 range. |
64
+ | `FL_ImageAddToBatch` | Combines two image batches into a single batch by concatenating them. Automatically resizes the second batch to match the first batch's dimensions using bicubic or area interpolation based on scaling direction. |
65
+ | `FL_ImageAdjuster` | Adjusts image properties including hue rotation (-180 to 180), saturation, brightness, contrast (all -100 to 100), and sharpness (0 to 100) using PIL's ImageEnhance. Converts to HSV for hue/saturation adjustments and applies UnsharpMask filter for sharpness, with real-time preview sent to the frontend. |
66
+ | `FL_ImageAspectCropper` | Crops images to a target aspect ratio (specified as width:height) by center-cropping either width or height as needed. Ensures resulting dimensions are even numbers for compatibility with video codecs. |
67
+ | `FL_ImageBatch` | Dynamically combines multiple images into a single batch with configurable number of inputs (2-100). Uses ComfyUI's ImageBatch node internally and automatically resizes images to match the first image's dimensions. |
68
+ | `FL_ImageBatchToGrid` | Arranges a batch of images into a grid layout with a specified number of images per row. Creates a single composite image with black background filling any empty grid positions. |
69
+ | `FL_ImageBlank` | Creates a blank image with specified width, height, and RGB color values. Generates a solid color image as a tensor suitable for use in ComfyUI workflows. |
70
+ | `FL_ImageCrop` | Crops images from specified directions (top, bottom, left, right, or combinations) by a specified pixel amount. Automatically validates crop amounts to prevent exceeding image dimensions. |
71
+ | `FL_ImageDimensionDisplay` | Extracts and returns the width and height dimensions of an input image as a formatted string. Supports both tensor and PIL image formats. |
72
+ | `FL_ImageListToImageBatch` | Converts a list of individual images into a single batched image tensor. Automatically resizes images to match the first image's dimensions using Lanczos interpolation if needed. |
73
+ | `FL_ImageNotes` | Adds a text bar with custom text to images, positioned at top or bottom. Supports configurable bar height, text size, borders, and optional word wrapping with automatic height adjustment to fit wrapped text. |
74
+ | `FL_ImageRandomizer` | Randomly selects an image or video from a specified directory based on a seed value (using modulo operation for deterministic selection). Supports subdirectory searching and returns the selected media as a batch along with the file path and filename. |
75
+ | `FL_ImageSelector` | Selects specific images from a batch using comma-separated indices or the 'last' keyword. Returns a new batch containing only the specified images in the order they were listed. |
76
+ | `FL_ImageSlicer` | Divides an image into a grid of equally-sized rectangular slices based on x and y subdivision counts. Returns all slices as a batch of images, processing from left-to-right, top-to-bottom. |
77
+ | `FL_LoadImage` | Provides a file browser interface for loading images from a custom directory structure with server-side API endpoints. Converts RGBA images to RGB with white background compositing and handles various image formats. |
78
+ | `FL_PaddingRemover` | Detects and removes uniform padding from images by analyzing edge colors and their consistency across rows and columns. Supports CPU and GPU processing modes, configurable tolerance, minimum content size constraints, and additional manual trimming options with optional debug visualization. |
79
+ | `FL_ReplaceColor` | Replaces pixels of a specific source color with a target color using Euclidean distance in RGB space and configurable tolerance. Supports morphological operations (expand/contract) to dilate or erode the replacement area using circular kernels. |
80
+ | `FL_SaveImages` | Saves images to a custom folder structure with templated filenames and automatic index incrementing to avoid overwriting. Supports optional metadata saving as separate text files alongside images. |
81
+ | `FL_SaveRGBAAnimatedWebP` | Saves animated WebP files from separate RGB and alpha channel image batches with configurable FPS, quality, and encoding method. Creates a preview with checkerboard background for transparency visualization and exports both the WebP animation and a ZIP file containing individual PNG frames with alpha. |
82
+ | `FL_SaveWebM` | Exports image batches as WebM video files using VP9 codec with configurable FPS, quality, and optional alpha channel preservation. Uses imageio with ffmpeg backend and includes fallback handling for encoding errors. |
83
+
84
+ ### 📷 Screenshots & Examples
85
+
86
+ ![🖼️ Image Nodes Example](images/nodes/image_nodes.png)
87
+
88
+ </details>
89
+
90
+ ---
91
+
92
+ <details>
93
+ <summary><h2 id="-captioning-nodes">📝 Captioning Nodes</h2></summary>
94
+
95
+ > *Nodes for generating, saving, and manipulating image and video captions.*
96
+
97
+ | Node | Description |
98
+ |------|-------------|
99
+ | `FL_CSVExtractor` | Extracts a specific column value from a randomly selected CSV row using a seed-based selection mechanism, supporting header skipping and returning the extracted text, row number, and full row data. Uses modulo-based pseudo-random selection for reproducible results. |
100
+ | `FL_CaptionSaver_V2` | Advanced caption saver supporting both image tensor input and directory input modes with single or multiple caption options, optional mask image saving, and configurable downsize factors. Provides flexible caption assignment with automatic list extension/truncation and unique filename generation when overwrite is disabled. |
101
+ | `FL_CaptionToCSV` | Scans an image directory and creates an in-memory CSV mapping image filenames to their corresponding caption text files. Returns CSV data as UTF-8 encoded bytes containing image_file and caption columns. |
102
+ | `FL_ImageCaptionLayout` | Creates a visual grid layout combining images with their caption files from a directory, generating a single composite image with configurable rows, image sizes, padding, and caption boxes. Returns a PyTorch tensor suitable for display in ComfyUI. |
103
+ | `FL_ImageCaptionLayoutPDF` | Generates both a PDF document and an image preview displaying a grid of images with captions from a directory, supporting pagination for multiple pages with configurable layout dimensions, orientation, and font settings. Uses ReportLab for PDF generation and PIL for image preview creation. |
104
+ | `FL_ImageCaptionSaver` | Saves a batch of images and their associated caption text to a specified folder, sanitizing captions by removing special characters and supporting optional file overwrite prevention. Handles tensor-to-image conversion with automatic grayscale-to-RGB conversion and proper value normalization. |
105
+ | `FL_LoadCSV` | Loads a CSV file from disk and returns both the raw binary data and row count for use in other nodes. Validates file existence, extension, and provides modification time tracking for cache invalidation. |
106
+ | `FL_MirrorAndAppendCaptions` | Processes images in a directory by appending frame numbers to captions and optionally creating horizontally mirrored duplicates with sequential frame numbering. Supports prepending or appending custom text to captions and saves both original and mirrored versions back to the directory. |
107
+ | `FL_OllamaCaptioner` | Generates image captions using Ollama LLM by encoding images as base64 and sending them to a local Ollama server for description generation. Saves images with either AI-generated or default captions, supporting custom model selection and URL configuration. |
108
+ | `FL_SaveCSV` | Writes CSV data (received as bytes) to a specified file path, automatically creating output directories and ensuring proper .csv extension. Provides file writing with error handling and console logging for save confirmation. |
109
+ | `FL_VideoCaptionSaver` | Converts a sequence of image tensors into a video file (MP4 or AVI) using OpenCV with configurable FPS and quality settings, while saving an associated caption text file. Handles RGB-to-BGR conversion, frame processing with progress tracking, and supports overwrite prevention. |
110
+ | `FL_WordFrequencyGraph` | Analyzes all text files in a directory to generate a horizontal bar graph visualization of word frequency statistics with customizable color schemes, word filtering options, and configurable output dimensions. Excludes common stop words and produces a dark-themed matplotlib graph as a PyTorch tensor. |
111
+
112
+ ### 📷 Screenshots & Examples
113
+
114
+ ![📝 Captioning Nodes Example](images/nodes/captioning_nodes.png)
115
+
116
+ </details>
117
+
118
+ ---
119
+
120
+ <details>
121
+ <summary><h2 id="-vfx-nodes">✨ VFX Nodes</h2></summary>
122
+
123
+ > *Nodes for applying visual effects to images.*
124
+
125
+ | Node | Description |
126
+ |------|-------------|
127
+ | `FL_Ascii` | Converts images to ASCII art by sampling pixels at regular intervals and mapping them to custom character sets, with options for sequential or brightness-based character selection, configurable spacing, font, and font size. |
128
+ | `FL_Dither` | Applies various dithering algorithms (Floyd-Steinberg, Random, Ordered, Bayer) to reduce images to a specified number of colors, creating retro-style color quantization effects with configurable color palette sizes from 2-256 colors. |
129
+ | `FL_Glitch` | Creates digital glitch effects using the glitch_this library with controllable glitch intensity and optional RGB color channel offset, applying effects both horizontally and vertically by rotating the image 90 degrees during processing. |
130
+ | `FL_HalftonePattern` | Generates halftone dot patterns by converting images to grayscale and creating circular dots of varying sizes based on region brightness, with configurable dot size and spacing parameters for newspaper-print style effects. |
131
+ | `FL_HexagonalPattern` | Creates mosaic-style images by tiling hexagonal crops of the input with configurable shadow effects, background color, rotation, and spacing using PIL's polygon drawing capabilities. |
132
+ | `FL_ImageCollage` | Generates photomosaics by tiling a template image across the base image, colorizing each tile based on the average color of the corresponding base region, with configurable tile size and spacing. |
133
+ | `FL_ImagePixelator` | Applies pixelation effects with morphological gradient edge detection using Kornia, featuring configurable scale factor, kernel size, and sine-wave modulation for animated pixelation intensity across image sequences. |
134
+ | `FL_InfiniteZoom` | Produces infinite zoom/droste effects using OpenGL shaders with GLFW, supporting configurable scale, mirror/swirl parameters, iteration count, and animation speed to create recursive visual patterns. |
135
+ | `FL_PaperDrawn` | Simulates hand-drawn sketch effects using OpenGL fragment shaders that apply directional gradient analysis with configurable angle count, sampling density, line width, and vignette strength to create pencil-drawn aesthetics. |
136
+ | `FL_PixelArtShader` | Creates pixel art effects by downsampling images with nearest-neighbor interpolation, applying color quantization, and optionally mapping to extracted color palettes using K-means clustering with mask support. |
137
+ | `FL_PixelSort` | Implements pixel sorting effects based on HSV saturation values, sorting pixels within detected edge intervals either horizontally or vertically with configurable threshold, smoothing, and rotation parameters. |
138
+ | `FL_RetroEffect` | Creates vintage CRT monitor effects by applying RGB color channel offset, scanline overlay, radial vignette with gaussian blur, and random noise blending using PIL image processing techniques. |
139
+ | `FL_Ripple` | Generates radial ripple/wave distortion effects using sinusoidal displacement mapping based on distance from a configurable center point, with adjustable amplitude, frequency, phase, and optional sine-wave modulation. |
140
+ | `FL_Shadertoy` | Renders Shadertoy-compatible GLSL shaders using OpenGL with support for up to 4 input image channels, iResolution/iTime/iFrame uniforms, and configurable frame count/FPS for shader-based generative effects. |
141
+ | `FL_TextOverlayNode` | Overlays customizable text on images with support for TrueType fonts (system or local), configurable RGB color, percentage-based positioning, multiple anchor points (9 positions), and multiline text rendering using PIL ImageDraw. |
142
+
143
+ ### 📷 Screenshots & Examples
144
+
145
+ ![✨ VFX Nodes Example](images/nodes/vfx_nodes.png)
146
+
147
+ </details>
148
+
149
+ ---
150
+
151
+ <details>
152
+ <summary><h2 id="-utility-nodes">🛠️ Utility Nodes</h2></summary>
153
+
154
+ > *General utility nodes for various tasks.*
155
+
156
+ | Node | Description |
157
+ |------|-------------|
158
+ | `FL_ClipScanner` | Tokenizes text prompts using OpenCLIP tokenizers for different model types (SDXL ViT-G/14, SD 1.5 ViT-L/14, FLUX ViT-L/14) and displays detailed token analysis including token count and decoded output. |
159
+ | `FL_CodeNode` | Executes arbitrary Python code provided as string input or loaded from file, with four generic output slots and dynamic input support via inputs/outputs dictionaries for custom algorithm integration. |
160
+ | `FL_DirectoryCrawl` | Recursively crawls directories to batch-load images or text files with progress tracking, returning images as both batched tensors (padded) and individual image lists for flexible processing. |
161
+ | `FL_Float` | Outputs a float value rounded to 2 decimal places, serving as a simple float constant provider for workflows. |
162
+ | `FL_InpaintCrop` | Crops images based on mask bounding boxes with multiple sizing modes (free, forced, range, long/short side) including context expansion, optional hole filling (CPU/GPU), and generates stitch data for recomposition. |
163
+ | `FL_Inpaint_Stitch` | Stitches inpainted images back into their original positions using crop data from FL_InpaintCrop, handling rescaling and alpha compositing to blend processed regions seamlessly. |
164
+ | `FL_JS` | Executes custom JavaScript code in response to ComfyUI workflow events (before_queued, after_queued, executing, executed, etc.) for client-side scripting integration. |
165
+ | `FL_Math` | Evaluates mathematical expressions with up to three variables (A, B, C) using safe AST parsing, supporting basic arithmetic operators (add, subtract, multiply, divide, power) and returning both integer and float results. |
166
+ | `FL_ModelInspector` | Inspects PyTorch checkpoint files (.ckpt, .safetensors) and extracts comprehensive information including parameter count, layer shapes, architecture analysis, and model structure with support for various loading methods and fallback mechanisms. |
167
+ | `FL_Padding` | Adds customizable padding to images on all four sides with configurable RGB color, optional alpha channel, and proper tensor handling for batched processing. |
168
+ | `FL_PasteByMask` | Pastes images onto base images at mask locations with advanced features including multiple resize behaviors (resize, keep_ratio_fill/fit, source_size), blend modes (normal, multiply, screen, overlay, etc.), feathering, and mask mapping support for batch processing. |
169
+ | `FL_PasteOnCanvas` | Pastes and centers masked images onto a canvas of specified dimensions with optional background color/image, supporting multiple resize algorithms (bilinear, nearest, bicubic, lanczos), padding, and alpha channel handling. |
170
+ | `FL_PathTypeChecker` | Analyzes file path strings to determine their type (absolute, relative, UNC, URL-like, drive-specific) with validation and classification logic. |
171
+ | `FL_RandomNumber` | Generates random integer and float values within specified ranges using seed-based reproducibility, with automatic seed generation when seed is 0. |
172
+ | `FL_SDUltimate_Slices` | Calculates slice dimensions for SD Ultimate upscaling by dividing images into configurable grid patterns (1x1 to 4x4) with multiplier support for slice size adjustment. |
173
+ | `FL_SeparateMaskComponents` | Separates multi-component masks into individual connected components using OpenCV's connected component labeling, returning separated masks and a mapping tensor for batch tracking. |
174
+ | `FL_Switch` | Implements lazy-evaluated boolean switch that evaluates and returns either on_true or on_false input based on switch value, enabling conditional workflow execution without evaluating unused branches. |
175
+ | `FL_Switch_Big` | Implements lazy-evaluated multi-case switch logic (5 cases + default) by comparing a switch condition against case strings and evaluating only the matched input path for conditional workflow branching. |
176
+ | `FL_SystemCheck` | Gathers and exposes system information including Python version, OS, CPU, RAM, GPU, library versions (PyTorch, transformers, etc.), and environment variables via an HTTP endpoint. |
177
+ | `FL_UnloadModel` | Removes models from memory and clears CUDA cache by unloading specified models from ComfyUI's model management system, with passthrough capability for workflow continuity. |
178
+ | `FL_VideoCropMask` | Crops video frames based on mask bounding boxes with temporal smoothing, maintaining aspect ratio and optionally applying padding, returning cropped video, mask, and crop data for each frame. |
179
+ | `FL_VideoRecompose` | Replaces cropped regions back into original video frames using crop data from FL_VideoCropMask, resizing processed frames to match original crop dimensions. |
180
+
181
+ ### 📷 Screenshots & Examples
182
+
183
+ ![🛠️ Utility Nodes Example](images/nodes/utility_nodes.png)
184
+
185
+ </details>
186
+
187
+ ---
188
+
189
+ <details>
190
+ <summary><h2 id="-ksamplers-nodes">🎲 KSamplers Nodes</h2></summary>
191
+
192
+ > *Nodes for sampling in the generation process.*
193
+
194
+ | Node | Description |
195
+ |------|-------------|
196
+ | `FL_KSamplerXYZPlot` | Grid comparison sampler that generates parameter sweep visualizations by iterating over X/Y axis values (steps, CFG, denoise, sampler, or scheduler) with optional Z-axis stacking (vertical/horizontal), producing labeled image grids with axes and parameter annotations for systematic parameter testing. |
197
+ | `FL_KsamplerBasic` | Simplified sampler node that accepts either latent or image input (with VAE encoding), performs standard KSampler operations with configurable steps/CFG/sampler/scheduler/denoise parameters, and outputs both latent and decoded image results. |
198
+ | `FL_KsamplerPlus` | Advanced tiled sampler that divides latent or image inputs into overlapping grid slices (configurable X/Y slices and overlap), processes each tile with optional region-specific conditioning (including ControlNet cropping), and blends results using cosine-weighted masks to eliminate seams. |
199
+ | `FL_KsamplerPlusV2` | Enhanced version of FL_KsamplerPlus with additional features including user-configurable conditioning strength multiplier, complete conditioning split across tiles (including pooled outputs and tensor-based conditioning), batch processing support for sliced conditioning, and optional debug information output. |
200
+ | `FL_KsamplerSettings` | Configuration node that outputs sampling parameters including aspect ratio dimensions (SD/XL/SVD presets with landscape/portrait rotation), batch size, two-pass step counts, CFG scales, denoise strength, scale factor, and sampler/scheduler selection. |
201
+ | `FL_SamplerStrings` | String generator node with boolean toggles for 27 sampler types (euler, dpm, heun, ddim, etc.) that outputs a comma-separated string of selected sampler names for batch processing workflows. |
202
+ | `FL_SchedulerStrings` | String generator node with boolean toggles for 7 scheduler types (normal, karras, exponential, sgm_uniform, simple, ddim_uniform, beta) that outputs a comma-separated string of selected scheduler names for batch processing workflows. |
203
+
204
+ ### 📷 Screenshots & Examples
205
+
206
+ ![🎲 KSamplers Nodes Example](images/nodes/ksamplers_nodes.png)
207
+
208
+ </details>
209
+
210
+ ---
211
+
212
+ <details>
213
+ <summary><h2 id="-pdf-nodes">📄 PDF Nodes</h2></summary>
214
+
215
+ > *Nodes for working with PDF files.*
216
+
217
+ | Node | Description |
218
+ |------|-------------|
219
+ | `FL_BulkPDFLoader` | Loads all PDF files from a specified directory path and returns them as a list of PDF data objects containing file metadata (path, filename, page count) and binary content. Validates that PDFs exist and can be read, collecting errors for any failed loads. |
220
+ | `FL_ImagesToPDF` | Converts ComfyUI image tensors into a single PDF document with configurable DPI and page size (A4/Letter/Legal), automatically scaling and centering each image to fit the page while maintaining aspect ratio. Returns an in-memory PDF data object. |
221
+ | `FL_PDFEncryptor` | Encrypts a PDF with user and owner passwords using PyPDF2, supporting 40-bit or 128-bit encryption with granular permission controls (printing, copying, commenting, form filling, assembly, content extraction). Returns an encrypted in-memory PDF data object. |
222
+ | `FL_PDFImageExtractor` | Extracts embedded images from PDF pages that meet minimum width/height thresholds, handling multiple compression formats (DCTDecode/JPEG, FlateDecode/PNG, JPXDecode/JPEG2000, LZWDecode). Returns extracted images as normalized PyTorch tensors in batch format [B, H, W, C]. |
223
+ | `FL_PDFLoader` | Loads a single PDF file from a specified file path and returns it as a PDF data object containing the file path, page count, and binary content. Validates file existence and PDF format before loading. |
224
+ | `FL_PDFMerger` | Merges two PDF data objects into a single combined PDF using PyPDF2's PdfMerger, appending the second PDF after the first. Returns the merged PDF as an in-memory data object with total page count. |
225
+ | `FL_PDFSaver` | Saves a PDF data object to disk at a specified directory path with a given filename, automatically creating the output directory if needed and appending '.pdf' extension if not present. Returns the full output file path. |
226
+ | `FL_PDFTextExtractor` | Extracts all text content from a PDF document by iterating through pages using PyPDF2's text extraction, combining text from all pages with double newlines as page separators. Returns the extracted text as a single string. |
227
+ | `FL_PDFToImages` | Converts PDF pages to images using PyMuPDF (fitz) with configurable DPI resolution, supporting both single PDFs and lists of PDFs. Returns all pages as normalized PyTorch image tensors concatenated into a single batch. |
228
+ | `FL_TextToPDF` | Generates a PDF document from plain text input using ReportLab canvas, with configurable page size, font size, margins, and title, automatically handling text wrapping and pagination. Returns an in-memory PDF data object with calculated page count. |
229
+
230
+ ### 📷 Screenshots & Examples
231
+
232
+ ![📄 PDF Nodes Example](images/nodes/pdf_nodes.png)
233
+
234
+ </details>
235
+
236
+ ---
237
+
238
+ <details>
239
+ <summary><h2 id="-gpt-nodes">🤖 GPT Nodes</h2></summary>
240
+
241
+ > *Nodes for integrating with GPT and OpenAI models.*
242
+
243
+ | Node | Description |
244
+ |------|-------------|
245
+ | `FL_Dalle3` | Generates images using OpenAI's DALL-E 3 model with asynchronous batch processing, caching results based on parameters to avoid redundant API calls, and returns image tensors along with revised prompts. Supports auto-save functionality with metadata JSON files and configurable retry logic for API failures. |
246
+ | `FL_GPT_Image1` | Generates or edits images using OpenAI's gpt-image-1 model with support for batch generation, image editing with optional masks, and comprehensive error handling that creates error images with visual text feedback. Implements retry logic, multipart form-data for edits endpoint, and processes both base64 and URL-based image responses. |
247
+ | `FL_GPT_Image1_ADV` | Advanced multi-input variant that generates multiple images concurrently using OpenAI's gpt-image-1 model by processing up to 100 prompts with individual image inputs for editing in parallel using async/await and thread pool execution. Each input slot can have its own prompt and optional image, with all outputs combined into a batched tensor and detailed per-call response logs. |
248
+ | `FL_GPT_Text` | Makes synchronous API calls to OpenAI's GPT models (GPT-4, GPT-3.5-turbo) for text completion with full parameter control including temperature, top_p, and frequency/presence penalties. Optionally saves responses to file and falls back to environment variable for API key if not provided. |
249
+ | `FL_GPT_Vision` | Batch processes images using OpenAI's GPT-4 Vision models to generate captions asynchronously with configurable batch sizes, supporting both input directories and image tensors, and saves captions to text files alongside images. Retrieves API key from environment variable OPENAI_API_KEY. |
250
+ | `FL_SimpleGPTVision` | Sends a single image to OpenAI's GPT-4 Vision API to generate a text caption based on configurable system and user prompts, with built-in rate limiting retry logic using exponential backoff. Returns the generated caption as a string output. |
251
+
252
+ ### 📷 Screenshots & Examples
253
+
254
+ ![🤖 GPT Nodes Example](images/nodes/gpt_nodes.png)
255
+
256
+ </details>
257
+
258
+ ---
259
+
260
+ <details>
261
+ <summary><h2 id="-ai-nodes">🧠 AI Nodes</h2></summary>
262
+
263
+ > *Nodes that integrate with various AI models and services.*
264
+
265
+ | Node | Description |
266
+ |------|-------------|
267
+ | `FL_Fal_Gemini_ImageEdit` | Edits up to 5 input images using Fal AI Gemini 2.5 Flash Image Edit API with multimodal prompt support, async processing, and automatic image URL generation. Returns edited images with URLs and description. |
268
+ | `FL_Fal_Kling_AIAvatar` | Generates AI avatar videos using Fal AI Kling Video API by combining input image with audio tensor or image sequence, with optional text prompt refinement. Returns extracted video frames and original audio. |
269
+ | `FL_Fal_Kontext` | Edits images using Fal AI Flux Pro Kontext API with multi-image input support (batching), asynchronous parallel processing, and configurable parameters including aspect ratio and safety tolerance. Returns batched edited images from multiple API calls. |
270
+ | `FL_Fal_Pixverse` | Generates videos from single image using Fal AI Pixverse v5 Image-to-Video API with style presets, camera movements, and parallel batch processing (up to 5). Returns extracted frames from generated videos as tensors. |
271
+ | `FL_Fal_Pixverse_LipSync` | Generates lip-sync videos using Fal AI Pixverse LipSync API supporting both audio input and text-to-speech modes with voice selection, processing video frames tensor with audio synchronization. Returns lip-synced video frames and audio. |
272
+ | `FL_Fal_Pixverse_Transition` | Creates transition videos between two images using Fal AI Pixverse v5 Transition API with configurable resolution, aspect ratio, and duration. Returns extracted frames from generated transition videos. |
273
+ | `FL_Fal_Seedance_i2v` | Generates videos from single image using Fal AI ByteDance Seedance v1 Pro Image-to-Video API with support for multi-segment prompts using [cut] markers, configurable resolution, duration, and camera settings. Returns all extracted frames from generated video. |
274
+ | `FL_Fal_Seedream_Edit` | Edits up to 10 images using Fal AI ByteDance Seedream v4 Edit API with custom or preset image sizes, auto-scaling to meet minimum dimensions while preserving aspect ratio. Returns edited images with URLs and seed information. |
275
+ | `FL_Fal_Sora` | Generates videos using Fal AI Sora 2 API supporting both text-to-video and image-to-video modes with optional OpenAI API key pass-through, automatic endpoint selection based on PRO mode, and audio extraction. Returns video frames, audio waveform, video URL, and status message. |
276
+ | `FL_GeminiImageEditor` | Generates or edits images using Google Gemini 2.5 Flash Image API with support for up to 4 reference images, batch generation with parallel async processing, and optional square padding. Returns list of generated images with detailed API response logs. |
277
+ | `FL_GeminiImageGenADV` | Advanced multi-input image generation using Google Gemini with dynamic input count (1-100), async parallel batch processing, and per-input prompt/image pairs. Returns list of generated images based on variable number of input slots. |
278
+ | `FL_GeminiTextAPI` | Generates text responses using Google Gemini models (2.5/2.0/1.5 variants) with configurable temperature, token limits, and optional system instructions. Returns raw text output without additional formatting. |
279
+ | `FL_GeminiVideoCaptioner` | Generates detailed captions for videos or image sequences using Google Gemini API, with automatic WebM conversion for API compatibility, frame extraction at configurable FPS, and support for audio processing. Returns caption text and sample frame from video. |
280
+ | `FL_Hedra_API` | Generates videos from image, audio file, and text prompt using Hedra API with configurable aspect ratio and resolution, automatic polling for generation completion, and frame extraction from downloaded video. Returns video frames tensor with processing logs. |
281
+ | `FL_HunyuanDelight` | Processes images using Hunyuan3D-2 model via Stable Diffusion InstructPix2Pix pipeline with configurable CFG, steps, and iterative refinement loops. Downloads the model from HuggingFace and applies image-to-image transformations without text prompts. |
282
+ | `FL_PixVerseAPI` | Generates videos from images using PixVerse API with support for standard image-to-video and transition modes, parallel batch processing with configurable seeds, and automatic frame extraction from generated MP4 videos. Returns up to 5 batches of extracted frames as tensors. |
283
+ | `FL_RunwayAct2` | Generates character performance videos using RunwayML Act Two API from input character images/videos and reference videos, with controls for body movement and expression intensity. Returns extracted video frames as tensors. |
284
+ | `FL_RunwayImageAPI` | Generates images using RunwayML Gen4 Image API with support for up to 3 reference images with custom tags, configurable generation parameters, and automatic polling for task completion. Returns generated image tensor and detailed status logs. |
285
+ | `FL_Veo3VideoGen` | Generates videos using Google Vertex AI Veo 3.0 models with service account authentication, optional reference image input, configurable aspect ratio/resolution, and automatic polling with frame extraction. Returns extracted video frames, video path, and processing logs. |
286
+ | `FL_VertexGemini25FlashImage` | Generates images using Google Vertex AI Gemini 2.5 Flash Image model with service account authentication, support for up to 3 reference images, and parallel batch generation. Returns batch tensor of generated images with detailed processing logs. |
287
+
288
+ ### 📷 Screenshots & Examples
289
+
290
+ ![🧠 AI Nodes Example](images/nodes/ai_nodes.png)
291
+
292
+ </details>
293
+
294
+ ---
295
+
296
+ <details>
297
+ <summary><h2 id="-audio-nodes">🔊 Audio Nodes</h2></summary>
298
+
299
+ > *Nodes for audio analysis, processing, and audio-reactive visual effects.*
300
+
301
+ | Node | Description |
302
+ |------|-------------|
303
+ | `FL_Audio_BPM_Analyzer` | Analyzes audio using librosa to detect BPM and beat positions, with options for two BPM calculation methods (beat_intervals or onset_strength), beat offset adjustment, and automatic beat filling to cover the entire audio duration. Outputs beat positions as JSON with visualization. |
304
+ | `FL_Audio_Beat_Visualizer` | Generates video frames that visualize beat patterns by either alternating between black/white on beat changes or cycling through provided images, with configurable frame dimensions and starting color. |
305
+ | `FL_Audio_Crop` | Crops audio waveforms to specified start and end times using MM:SS or seconds format, with automatic clamping to valid audio boundaries. |
306
+ | `FL_Audio_Drum_Detector` | Detects kicks, snares, and hi-hats from audio using librosa onset detection with frequency band analysis (kicks: 30-300Hz, snares: 150-400Hz + 4-10kHz noise, hi-hats: 6kHz+) and adjustable sensitivity thresholds. |
307
+ | `FL_Audio_Envelope_Visualizer` | Visualizes audio envelopes as grayscale video frames where pixel intensity corresponds to envelope values, with configurable intensity multiplier and optional color inversion. |
308
+ | `FL_Audio_Music_Video_Sequencer` | Generates complete music video shot sequences from beat positions using pattern-based orchestration (A/B/C/D patterns with configurable beat counts), creating drift-free frame boundaries and detailed metadata for each shot including time, beat, and sample boundaries. |
309
+ | `FL_Audio_Reactive_Brightness` | Multiplies frame pixel values by brightness factors calculated from audio envelopes, with configurable base brightness, intensity scaling, optional inversion, and output clamping. |
310
+ | `FL_Audio_Reactive_Edge_Glow` | Applies audio-reactive edge detection using Sobel operators (or accepts pre-computed edge frames) and adds colored glow effects that pulse with envelope values, supporting multiple blend modes (add, screen, overlay) and glow colors. |
311
+ | `FL_Audio_Reactive_Envelope` | Generates per-frame ADSR envelopes (Attack, Decay, Sustain, Release) from drum detection times (kicks, snares, hi-hats) with independent configurable envelope parameters for each drum type. |
312
+ | `FL_Audio_Reactive_Saturation` | Adjusts color saturation by blending between grayscale (using Rec. 709 luma coefficients) and original frames based on envelope-modulated saturation values, supporting both saturation and desaturation effects. |
313
+ | `FL_Audio_Reactive_Scale` | Applies audio-reactive zoom/scale effects to frames based on envelope values, with center-cropping or padding to maintain dimensions and configurable interpolation modes (bilinear, bicubic, nearest). |
314
+ | `FL_Audio_Reactive_Speed` | Time-remaps frames using cumulative speed multipliers derived from audio envelopes, allowing for dynamic speed-up/slow-down effects with frame interpolation and optional envelope inversion. |
315
+ | `FL_Audio_Segment_Extractor` | Extracts audio segments based on pre-analyzed beat positions from the BPM analyzer, supporting drift-free frame alignment by using cumulative time mapping and outputting precise frame counts for video synchronization. |
316
+ | `FL_Audio_Separation` | Separates audio into four stems (bass, drums, other, vocals) using the Hybrid Demucs model from torchaudio, with chunked processing to manage memory usage and configurable overlap/fade parameters. |
317
+ | `FL_Audio_Shot_Iterator` | Extracts individual shot metadata (frame counts, beat ranges, time boundaries) from music video sequence JSON by shot index, designed for iterative processing of video sequences. |
318
+
319
+ ### 📷 Screenshots & Examples
320
+
321
+ ![🔊 Audio Nodes Example](images/nodes/audio_nodes.png)
322
+
323
+ </details>
324
+
325
+ ---
326
+
327
+ <details>
328
+ <summary><h2 id="-experimental-nodes">🧪 Experimental Nodes</h2></summary>
329
+
330
+ > *Experimental nodes with various functionalities.*
331
+
332
+ | Node | Description |
333
+ |------|-------------|
334
+ | `FL_BatchAlign` | Patches a model to enable batch-aligned generation by applying style alignment techniques through shared attention mechanisms and normalization layers. Uses adaptive instance normalization (AdaIN) on queries, keys, and values with configurable attention sharing and normalization strategies (group/layer/both). |
335
+ | `FL_ColorPicker` | A simple utility node that accepts a hex color string input and passes it through as output, designed to facilitate color selection in workflows. |
336
+ | `FL_GradGenerator` | Generates gradient images from a JSON-formatted color stops specification with position and color values. Supports RGB/HSV color modes and multiple interpolation curves (Linear, Ease In, Ease Out, Ease In-Out) with configurable dimensions. |
337
+ | `FL_NFTGenerator` | Randomly selects images from a directory based on rarity percentages encoded in filenames (format: name-XXXper-val), using weighted probability selection with a configurable seed. Returns both the selected image and its corresponding mask file (or blank mask if not found). |
338
+
339
+ ### 📷 Screenshots & Examples
340
+
341
+ ![🧪 Experimental Nodes Example](images/nodes/experiments_nodes.png)
342
+
343
+ </details>
344
+
345
+ ---
346
+
347
+ <details>
348
+ <summary><h2 id="-prompting-nodes">💬 Prompting Nodes</h2></summary>
349
+
350
+ > *Nodes for generating and manipulating prompts.*
351
+
352
+ | Node | Description |
353
+ |------|-------------|
354
+ | `FL_MadLibGenerator` | Generates text by replacing up to 5 different delimiter patterns in a template with randomly selected words from corresponding word lists. Uses per-list seeding with MD5 hashing to ensure reproducible but independent randomization for each delimiter. |
355
+ | `FL_PromptBasic` | Concatenates three text strings (prepend, prompt, append) without adding any spaces, preserving user-specified formatting for prompt construction. |
356
+ | `FL_PromptMulti` | Processes multi-line positive and negative prompts into parallel lists, automatically balancing counts by repeating the last prompt or using empty strings. Generates indexed names with configurable prefix and outputs as lists for batch processing. |
357
+ | `FL_PromptSelector` | Selects a single prompt line by index from a multi-line prompt string, optionally prepending and appending text with automatic space insertion. |
358
+
359
+ ### 📷 Screenshots & Examples
360
+
361
+ ![💬 Prompting Nodes Example](images/nodes/prompting_nodes.png)
362
+
363
+ </details>
364
+
365
+ ---
366
+
367
+ <details>
368
+ <summary><h2 id="-file-operation-nodes">📂 File Operation Nodes</h2></summary>
369
+
370
+ > *Nodes for file operations.*
371
+
372
+ | Node | Description |
373
+ |------|-------------|
374
+ | `FL_ZipDirectory` | Creates a ZIP archive of an entire directory structure in memory using ZIP_DEFLATED compression, returning the raw bytes without writing to disk. |
375
+ | `FL_ZipSave` | Compresses a directory into a ZIP file and saves it to a specified output location with automatic filename collision handling via timestamp suffixing. |
376
+
377
+ ### 📷 Screenshots & Examples
378
+
379
+ ![📂 File Operation Nodes Example](images/nodes/fileoperations_nodes.png)
380
+
381
+ </details>
382
+
383
+ ---
384
+
385
+ <details>
386
+ <summary><h2 id="-google-drive-nodes">☁️ Google Drive Nodes</h2></summary>
387
+
388
+ > *Nodes for Google Cloud services integration.*
389
+
390
+ | Node | Description |
391
+ |------|-------------|
392
+ | `FL_GoogleCloudStorage` | Uploads images or compiled videos to Google Cloud Storage buckets using service account credentials. Supports batch image uploads, video compilation with configurable codecs/FPS, public/private access control, and custom metadata attachment. |
393
+ | `FL_GoogleDriveDownloader` | Downloads files from Google Drive using share links, automatically extracts ZIP archives, and manages output in organized directory structures with cleanup of temporary files. |
394
+ | `FL_GoogleDriveImageDownloader` | Downloads images from Google Drive share links with optional local caching system using MD5-hashed index. Converts downloaded images to RGB tensors normalized to [0,1] range with configurable cache behavior. |
395
+
396
+ ### 📷 Screenshots & Examples
397
+
398
+ ![☁️ Google Drive Nodes Example](images/nodes/googledrive_nodes.png)
399
+
400
+ </details>
401
+
402
+ ---
403
+
404
+ <details>
405
+ <summary><h2 id="-api-tool-nodes">🔌 API Tool Nodes</h2></summary>
406
+
407
+ > *Nodes for API interactions.*
408
+
409
+ | Node | Description |
410
+ |------|-------------|
411
+ | `FL_API_Base64_ImageLoader` | Decodes base64-encoded images (with automatic data URL prefix removal) and converts them to ComfyUI image tensors. Supports optional resizing with aspect ratio preservation and returns image tensor with dimensions, job_id, user_id, and category. |
412
+ | `FL_API_ImageSaver` | Saves images to a categorized directory structure (base/category/user_id/job_id.format) with support for PNG, JPG, JPEG, and WebP formats and configurable quality settings. Returns full path, job_id, user_id, and category for API workflows. |
413
+
414
+ ### 📷 Screenshots & Examples
415
+
416
+ ![🔌 API Tool Nodes Example](images/nodes/apitools_nodes.png)
417
+
418
+ </details>
419
+
420
+ ---
421
+
422
+ <details>
423
+ <summary><h2 id="-hugging-face-nodes">🤗 Hugging Face Nodes</h2></summary>
424
+
425
+ > *Nodes for integrating with Hugging Face.*
426
+
427
+ | Node | Description |
428
+ |------|-------------|
429
+ | `FL_HFDatasetDownloader` | Downloads Hugging Face repositories (datasets, models, or spaces) using snapshot_download with configurable parallel workers and local directory specification. |
430
+ | `FL_HFHubModelUploader` | Uploads models and assets to Hugging Face Hub with automatic README generation, model card header support, and organized file structure. Handles images, ZIP files, and large model files with threaded progress tracking and retry logic. |
431
+ | `FL_HF_Character` | Uploads character-related assets (LoRA, datasets, captions, CSVs) to Hugging Face Hub using a structured path format (studio/project/character) for organized character library management. |
432
+ | `FL_HF_UploaderAbsolute` | Uploads various file types (LoRA files, ZIP datasets, images, PDFs, CSVs) to Hugging Face repositories at specified paths with progress tracking. Supports repository creation and uses environment variable HUGGINGFACE_API_KEY for authentication. |
433
+
434
+ ### 📷 Screenshots & Examples
435
+
436
+ ![🤗 Hugging Face Nodes Example](images/nodes/huggingface_nodes.png)
437
+
438
+ </details>
439
+
440
+ ---
441
+
442
+ <details>
443
+ <summary><h2 id="-loader-nodes">⏬ Loader Nodes</h2></summary>
444
+
445
+ > *Nodes for loading various resources.*
446
+
447
+ | Node | Description |
448
+ |------|-------------|
449
+ | `FL_NodeLoader` | A pass-through node that accepts and returns a TRIGGER type, designed for node dependency management in workflows. |
450
+ | `FL_NodePackLoader` | A pass-through node with IS_CHANGED set to float('NaN') to ensure it always processes when triggered, useful for forcing workflow execution. |
451
+ | `FL_UpscaleModel` | Upscales images in configurable batches using loaded upscale models with precision control (auto/32/16/bfloat16), optional downscaling by factor, multiple rescale methods (nearest-exact, bilinear, area, bicubic, lanczos), and TQDM progress tracking. |
452
+
453
+ ### 📷 Screenshots & Examples
454
+
455
+ ![⏬ Loader Nodes Example](images/nodes/loaders_nodes.png)
456
+
457
+ </details>
458
+
459
+ ---
460
+
461
+ <details>
462
+ <summary><h2 id="-discord-nodes">💬 Discord Nodes</h2></summary>
463
+
464
+ > *Nodes for Discord integration.*
465
+
466
+ | Node | Description |
467
+ |------|-------------|
468
+ | `FL_SendToDiscordWebhook` | Sends single images or video compilations to Discord via webhooks with configurable bot username, custom messages, user mentions (via Discord user IDs), FPS control for videos, and optional local file retention. |
469
+
470
+ ### 📷 Screenshots & Examples
471
+
472
+ ![💬 Discord Nodes Example](images/nodes/discord_nodes.png)
473
+
474
+ </details>
475
+
476
+ ---
477
+
478
+ <details>
479
+ <summary><h2 id="-work-in-progress-nodes">🚧 Work-in-Progress Nodes</h2></summary>
480
+
481
+ > *Nodes that are still in development.*
482
+
483
+ | Node | Description |
484
+ |------|-------------|
485
+ | `FL_FractalKSampler` | Experimental recursive K-sampler that generates images through fractal upscaling and slicing. Upscales latents, divides into 4 quadrants, recursively samples each with reduced denoise, and composites results with configurable blend factors. |
486
+ | `FL_TimeLine` | Work-in-progress timeline processor node for video animation with IPAdapter preset selection, dimension control, interpolation modes, and frame/FPS settings. Includes API endpoint for timeline data but currently returns model unchanged. |
487
+ | `FL_WF_Agent` | Workflow agent node that executes a node scanner to generate cached node definitions for AI-assisted workflow manipulation. Runs scanner as subprocess and provides feedback on cache file creation and status. |
488
+ | `FL_WanFirstLastFrameToVideo` | Enhanced WAN (Warp and Noise) implementation for video generation from first and last frames with advanced timing control. Supports custom keyframe positioning, temporal interpolation curves (linear, ease, bounce), regional masking, and CLIP vision conditioning. |
489
+
490
+ ### 📷 Screenshots & Examples
491
+
492
+ ![🚧 Work-in-Progress Nodes Example](images/nodes/wip_nodes.png)
493
+
494
+ </details>
495
+
496
+ ---
497
+
498
+ <details>
499
+ <summary><h2 id="-game-nodes">🎮 Game Nodes</h2></summary>
500
+
501
+ > *Nodes implementing games.*
502
+
503
+ | Node | Description |
504
+ |------|-------------|
505
+ | `FL_BulletHellGame` | Placeholder game node with no implementation, designed as a stub for future bullet hell game functionality. |
506
+ | `FL_TetrisGame` | Placeholder game node with no implementation, designed as a stub for future Tetris game functionality. |
507
+
508
+ ### 📷 Screenshots & Examples
509
+
510
+ ![🎮 Game Nodes Example](images/nodes/games_nodes.png)
511
+
512
+ </details>
513
+
514
+ ---
515
+
516
+ <details>
517
+ <summary><h2 id="-video-nodes">🎬 Video Nodes</h2></summary>
518
+
519
+ > *Nodes for video processing and frame interpolation.*
520
+
521
+ | Node | Description |
522
+ |------|-------------|
523
+ | `FL_FILM` | Frame interpolation using FILM (Frame Interpolation for Large Motion) from Google Research. Downloads TorchScript model from HuggingFace on first use, generates intermediate frames with configurable multiplier, and uses timestep-based interpolation for smooth motion. |
524
+ | `FL_ProResVideo` | Converts image batches to ProRes 4444 video files using FFmpeg with high-quality encoding (yuva444p10le pixel format, 8000 bits_per_mb). Automatically handles temporary file creation, unique naming with timestamp collision avoidance, and cleanup. |
525
+ | `FL_RIFE` | Frame interpolation using RIFE (Real-Time Intermediate Flow Estimation) v4.7 architecture. Downloads model weights from HuggingFace, supports multiple checkpoints (rife47, rife49), configurable multiplier, optional ensemble mode for quality, and multi-scale flow estimation. |
526
+ | `FL_VideoBatchSplitter` | Splits a video batch into exactly N equal-sized sub-batches with strict frame count validation. Returns up to 20 separate batch outputs with configurable frames per batch, requiring exact division with no remainders. |
527
+ | `FL_VideoCadence` | Analyzes image batches for scene changes and returns comma-separated frame counts per scene. Uses configurable detection methods (intensity, histogram, or hybrid) with GPU acceleration support, downsampling optimization, and minimum scene length enforcement. |
528
+ | `FL_VideoCadenceCompile` | Loads videos from a directory, crops each video from the middle to match specified frame counts from a cadence list, and concatenates all frames into a single image batch. Validates frame counts and dimensions with error handling. |
529
+ | `FL_VideoCrossfade` | Blends two video sequences with configurable crossfade duration using multiple blend modes (normal, multiply, screen, overlay, soft_light, add, subtract). Resizes both inputs to target dimensions and generates smooth transitions between sequences. |
530
+ | `FL_VideoCut` | Detects scene cuts in image batches and exports each scene as a separate MP4 file using parallel FFmpeg processing. Features optimized scene detection (intensity/histogram/hybrid), GPU acceleration, downsample optimization, and direct frame piping to FFmpeg for performance. |
531
+ | `FL_VideoTrim` | Trims specified numbers of frames from the start and end of an image batch, returning the trimmed video along with separate outputs for removed start and end frames. |
532
+
533
+ ### 📷 Screenshots & Examples
534
+
535
+ ![🎬 Video Nodes Example](images/nodes/video_nodes.png)
536
+
537
+ </details>
538
+
539
+ ---
custom_nodes/ComfyUI_Fill-Nodes/__init__.py ADDED
@@ -0,0 +1,635 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AI NODES
2
+ from .nodes.ai.FL_Fal_Gemini_ImageEdit import FL_Fal_Gemini_ImageEdit
3
+ from .nodes.ai.FL_Fal_Kling_AIAvatar import FL_Fal_Kling_AIAvatar
4
+ from .nodes.ai.FL_Fal_Kontext import FL_Fal_Kontext
5
+ from .nodes.ai.FL_Fal_Pixverse import FL_Fal_Pixverse
6
+ from .nodes.ai.FL_Fal_Pixverse_LipSync import FL_Fal_Pixverse_LipSync
7
+ from .nodes.ai.FL_Fal_Pixverse_Transition import FL_Fal_Pixverse_Transition
8
+ from .nodes.ai.FL_Fal_Seedance_i2v import FL_Fal_Seedance_i2v
9
+ from .nodes.ai.FL_Fal_Seedream_Edit import FL_Fal_Seedream_Edit
10
+ from .nodes.ai.FL_Fal_SeedVR_Upscale import FL_Fal_SeedVR_Upscale
11
+ from .nodes.ai.FL_Fal_Sora import FL_Fal_Sora
12
+ from .nodes.ai.FL_GeminiImageEditor import FL_GeminiImageEditor
13
+ from .nodes.ai.FL_GeminiImageGenADV import FL_GeminiImageGenADV
14
+ from .nodes.ai.FL_GeminiTextAPI import FL_GeminiTextAPI
15
+ from .nodes.ai.FL_GeminiVideoCaptioner import FL_GeminiVideoCaptioner
16
+ from .nodes.ai.FL_Hedra_API import FL_Hedra_API
17
+ from .nodes.ai.FL_PixVerseAPI import FL_PixVerseAPI
18
+ from .nodes.ai.FL_RunwayAct2 import FL_RunwayAct2
19
+ from .nodes.ai.FL_RunwayImageAPI import FL_RunwayImageAPI
20
+ from .nodes.ai.FL_VertexGemini25FlashImage import FL_VertexGemini25FlashImage
21
+ from .nodes.ai.FL_VertexVeo3 import FL_Veo3VideoGen
22
+
23
+ # API_TOOLS NODES
24
+ from .nodes.api_tools.FL_API_Base64_ImageLoader import FL_API_Base64_ImageLoader
25
+ from .nodes.api_tools.FL_API_ImageSaver import FL_API_ImageSaver
26
+
27
+ # AUDIO NODES
28
+ from .nodes.audio.FL_Audio_BPM_Analyzer import FL_Audio_BPM_Analyzer
29
+ from .nodes.audio.FL_Audio_Beat_Visualizer import FL_Audio_Beat_Visualizer
30
+ from .nodes.audio.FL_Audio_Crop import FL_Audio_Crop
31
+ from .nodes.audio.FL_Audio_Drum_Detector import FL_Audio_Drum_Detector
32
+ from .nodes.audio.FL_Audio_Envelope_Visualizer import FL_Audio_Envelope_Visualizer
33
+ from .nodes.audio.FL_Audio_Music_Video_Sequencer import FL_Audio_Music_Video_Sequencer
34
+ from .nodes.audio.FL_Audio_Reactive_Brightness import FL_Audio_Reactive_Brightness
35
+ from .nodes.audio.FL_Audio_Reactive_Edge_Glow import FL_Audio_Reactive_Edge_Glow
36
+ from .nodes.audio.FL_Audio_Reactive_Envelope import FL_Audio_Reactive_Envelope
37
+ from .nodes.audio.FL_Audio_Reactive_Saturation import FL_Audio_Reactive_Saturation
38
+ from .nodes.audio.FL_Audio_Reactive_Scale import FL_Audio_Reactive_Scale
39
+ from .nodes.audio.FL_Audio_Reactive_Speed import FL_Audio_Reactive_Speed
40
+ from .nodes.audio.FL_Audio_Segment_Extractor import FL_Audio_Segment_Extractor
41
+ from .nodes.audio.FL_Audio_Separation import FL_Audio_Separation
42
+ from .nodes.audio.FL_Audio_Shot_Iterator import FL_Audio_Shot_Iterator
43
+
44
+ # CAPTIONING NODES
45
+ from .nodes.captioning.FL_CSVExtractor import FL_CSVExtractor
46
+ from .nodes.captioning.FL_CaptionToCSV import FL_CaptionToCSV
47
+ from .nodes.captioning.FL_Caption_Saver_V2 import FL_CaptionSaver_V2
48
+ from .nodes.captioning.FL_ImageCaptionLayout import FL_ImageCaptionLayout
49
+ from .nodes.captioning.FL_ImageCaptionLayoutPDF import FL_ImageCaptionLayoutPDF
50
+ from .nodes.captioning.FL_Image_Caption_Saver import FL_ImageCaptionSaver
51
+ from .nodes.captioning.FL_LoadCSV import FL_LoadCSV
52
+ from .nodes.captioning.FL_MirrorAndAppendCaptions import FL_MirrorAndAppendCaptions
53
+ from .nodes.captioning.FL_OllamaCaptioner import FL_OllamaCaptioner
54
+ from .nodes.captioning.FL_SaveCSV import FL_SaveCSV
55
+ from .nodes.captioning.FL_Video_Caption_Saver import FL_VideoCaptionSaver
56
+ from .nodes.captioning.FL_WordFrequencyGraph import FL_WordFrequencyGraph
57
+
58
+ # DISCORD NODES
59
+ from .nodes.discord.FL_DiscordWebhook import FL_SendToDiscordWebhook
60
+
61
+ # EXPERIMENTS NODES
62
+ from .nodes.experiments.FL_BatchAligned import FL_BatchAlign
63
+ from .nodes.experiments.FL_ColorPicker import FL_ColorPicker
64
+ from .nodes.experiments.FL_GradGen import FL_GradGenerator
65
+ from .nodes.experiments.FL_NFTGenerator import FL_NFTGenerator
66
+
67
+ # FILE_OPERATIONS NODES
68
+ from .nodes.file_operations.FL_ZipDirectory import FL_ZipDirectory
69
+ from .nodes.file_operations.FL_ZipSave import FL_ZipSave
70
+
71
+ # GAMES NODES
72
+ from .nodes.games.FL_BulletHellGame import FL_BulletHellGame
73
+ from .nodes.games.FL_TetrisGame import FL_TetrisGame
74
+
75
+ # GOOGLE_DRIVE NODES
76
+ from .nodes.google_drive.FL_GoogleCloudStorage import FL_GoogleCloudStorage
77
+ from .nodes.google_drive.FL_GoogleDriveDownloader import FL_GoogleDriveDownloader
78
+ from .nodes.google_drive.FL_GoogleDriveImageDownloader import FL_GoogleDriveImageDownloader
79
+
80
+ # GPT NODES
81
+ from .nodes.gpt.FL_Dalle3 import FL_Dalle3
82
+ from .nodes.gpt.FL_GPT_Image1 import FL_GPT_Image1
83
+ from .nodes.gpt.FL_GPT_Image1_ADV import FL_GPT_Image1_ADV
84
+ from .nodes.gpt.FL_GPT_Text import FL_GPT_Text
85
+ from .nodes.gpt.FL_GPT_Vision import FL_GPT_Vision
86
+ from .nodes.gpt.FL_SimpleGPTVision import FL_SimpleGPTVision
87
+
88
+ # HUGGING_FACE NODES
89
+ from .nodes.hugging_face.FL_HFDatasetDownloader import FL_HFDatasetDownloader
90
+ from .nodes.hugging_face.FL_HFHubModelUploader import FL_HFHubModelUploader
91
+ from .nodes.hugging_face.FL_HF_Character import FL_HF_Character
92
+ from .nodes.hugging_face.FL_HF_UploaderAbsolute import FL_HF_UploaderAbsolute
93
+
94
+ # KARTEL NODES
95
+ from .nodes.kartel.FL_KartelJobInput import FL_KartelJobInput
96
+ from .nodes.kartel.FL_KartelJobOutput import FL_KartelJobOutput
97
+
98
+ # IMAGE NODES
99
+ from .nodes.image.FL_AnimeLineExtractor import FL_AnimeLineExtractor
100
+ from .nodes.image.FL_ApplyMask import FL_ApplyMask
101
+ from .nodes.image.FL_BlackFrameReject import FL_BlackFrameReject
102
+ from .nodes.image.FL_ImageAddNoise import FL_ImageAddNoise
103
+ from .nodes.image.FL_ImageAdjuster import FL_ImageAdjuster
104
+ from .nodes.image.FL_ImageAspectCropper import FL_ImageAspectCropper
105
+ from .nodes.image.FL_ImageBatch import FL_ImageBatch
106
+ from .nodes.image.FL_ImageBatchListConverter import FL_ImageListToImageBatch, FL_ImageBatchToImageList
107
+ from .nodes.image.FL_ImageBatchToGrid import FL_ImageBatchToGrid
108
+ from .nodes.image.FL_ImageNotes import FL_ImageNotes
109
+ from .nodes.image.FL_ImageOverlay import FL_ImageOverlay
110
+ from .nodes.image.FL_ImageSelector import FL_ImageSelector
111
+ from .nodes.image.FL_ImagePicker import FL_ImagePicker
112
+ from .nodes.image.FL_ImageSlicer import FL_ImageSlicer
113
+ from .nodes.image.FL_Image_AddToBatch import FL_ImageAddToBatch
114
+ from .nodes.image.FL_Image_Blank import FL_ImageBlank
115
+ from .nodes.image.FL_Image_Crop import FL_ImageCrop
116
+ from .nodes.image.FL_Image_Dimension_Display import FL_ImageDimensionDisplay
117
+ from .nodes.image.FL_Image_Randomizer import FL_ImageRandomizer
118
+ from .nodes.image.FL_LoadImage import FL_LoadImage
119
+ from .nodes.image.FL_PaddingRemover import FL_PaddingRemover
120
+ from .nodes.image.FL_ReplaceColor import FL_ReplaceColor
121
+ from .nodes.image.FL_SaveAndDisplayImage import FL_SaveAndDisplayImage
122
+ from .nodes.image.FL_SaveImages import FL_SaveImages
123
+ from .nodes.image.FL_SaveRGBAAnimatedWebP import FL_SaveRGBAAnimatedWebP
124
+ from .nodes.image.FL_SaveWebM import FL_SaveWebM
125
+ from .nodes.image.FL_SaveWebpImages import FL_SaveWebPImage
126
+
127
+ # KSAMPLERS NODES
128
+ from .nodes.ksamplers.FL_KsamplerBasic import FL_KsamplerBasic
129
+ from .nodes.ksamplers.FL_KsamplerPlus import FL_KsamplerPlus
130
+ from .nodes.ksamplers.FL_KsamplerPlusV2 import FL_KsamplerPlusV2
131
+ from .nodes.ksamplers.FL_KsamplerSettings import FL_KsamplerSettings
132
+ from .nodes.ksamplers.FL_SamplerStrings import FL_SamplerStrings
133
+ from .nodes.ksamplers.FL_SchedulerStrings import FL_SchedulerStrings
134
+ from .nodes.ksamplers.FL_KSamplerXYZPlot import FL_KSamplerXYZPlot
135
+
136
+ # LOADERS NODES
137
+ from .nodes.loaders.FL_NodeLoader import FL_NodeLoader
138
+ from .nodes.loaders.FL_NodePackLoader import FL_NodePackLoader
139
+ from .nodes.loaders.FL_UpscaleModel import FL_UpscaleModel
140
+
141
+ # PDF NODES
142
+ from .nodes.pdf.FL_BulkPDFLoader import FL_BulkPDFLoader
143
+ from .nodes.pdf.FL_ImagesToPDF import FL_ImagesToPDF
144
+ from .nodes.pdf.FL_PDFEncryptor import FL_PDFEncryptor
145
+ from .nodes.pdf.FL_PDFImageExtractor import FL_PDFImageExtractor
146
+ from .nodes.pdf.FL_PDFLoader import FL_PDFLoader
147
+ from .nodes.pdf.FL_PDFMerger import FL_PDFMerger
148
+ from .nodes.pdf.FL_PDFSaver import FL_PDFSaver
149
+ from .nodes.pdf.FL_PDFTextExtractor import FL_PDFTextExtractor
150
+ from .nodes.pdf.FL_PDFToImage import FL_PDFToImages
151
+ from .nodes.pdf.FL_TextToPDF import FL_TextToPDF
152
+
153
+ # PROMPTING NODES
154
+ from .nodes.prompting.FL_MadLibGenerator import FL_MadLibGenerator
155
+ from .nodes.prompting.FL_Prompt import FL_PromptBasic
156
+ from .nodes.prompting.FL_PromptMulti import FL_PromptMulti
157
+ from .nodes.prompting.FL_PromptSelector import FL_PromptSelector
158
+ from .nodes.prompting.FL_PromptSelectorBasic import FL_PromptSelectorBasic
159
+
160
+ # UTILITY NODES
161
+ from .nodes.utility.FL_ClipScanner import FL_ClipScanner
162
+ from .nodes.utility.FL_Code_Node import FL_CodeNode
163
+ from .nodes.utility.FL_DirectoryCrawl import FL_DirectoryCrawl
164
+ from .nodes.utility.FL_Float import FL_Float
165
+ from .nodes.utility.FL_InpaintCrop import FL_InpaintCrop
166
+ from .nodes.utility.FL_InpaintCrop import FL_Inpaint_Stitch
167
+ from .nodes.utility.FL_JS import FL_JS
168
+ from .nodes.utility.FL_Math import FL_Math
169
+ from .nodes.utility.FL_ModelInspector import FL_ModelInspector
170
+ from .nodes.utility.FL_NumberConverter import FL_IntToFloat, FL_FloatToInt
171
+ from .nodes.utility.FL_Padding import FL_Padding
172
+ from .nodes.utility.FL_PasteByMask import FL_PasteByMask
173
+ from .nodes.utility.FL_PasteOnCanvas import FL_PasteOnCanvas
174
+ from .nodes.utility.FL_PathTypeChecker import FL_PathTypeChecker
175
+ from .nodes.utility.FL_RandomRange import FL_RandomNumber
176
+ from .nodes.utility.FL_RandomShapeGenerator import FL_RandomShapeGenerator
177
+ from .nodes.utility.FL_SD_Slices import FL_SDUltimate_Slices
178
+ from .nodes.utility.FL_SeparateMasks import FL_SeparateMaskComponents
179
+ from .nodes.utility.FL_Switch import FL_Switch
180
+ from .nodes.utility.FL_Switch_Big import FL_Switch_Big
181
+ from .nodes.utility.FL_SystemCheck import FL_SystemCheck
182
+ from .nodes.utility.FL_UnloadModel import FL_UnloadModel, FL_UnloadAllModels
183
+ from .nodes.utility.FL_VideoCropNStitch import FL_VideoCropMask
184
+ from .nodes.utility.FL_VideoCropNStitch import FL_VideoRecompose
185
+
186
+ # VFX NODES
187
+ from .nodes.vfx.FL_Ascii import FL_Ascii
188
+ from .nodes.vfx.FL_Dither import FL_Dither
189
+ from .nodes.vfx.FL_Glitch import FL_Glitch
190
+ from .nodes.vfx.FL_HalfTone import FL_HalftonePattern
191
+ from .nodes.vfx.FL_HexagonalPattern import FL_HexagonalPattern
192
+ from .nodes.vfx.FL_ImageCollage import FL_ImageCollage
193
+ from .nodes.vfx.FL_Image_Pixelator import FL_ImagePixelator
194
+ from .nodes.vfx.FL_InfiniteZoom import FL_InfiniteZoom
195
+ from .nodes.vfx.FL_PaperDrawn import FL_PaperDrawn
196
+ from .nodes.vfx.FL_PixelArt import FL_PixelArtShader
197
+ from .nodes.vfx.FL_PixelSort import FL_PixelSort
198
+ from .nodes.vfx.FL_RetroEffect import FL_RetroEffect
199
+ from .nodes.vfx.FL_Ripple import FL_Ripple
200
+ from .nodes.vfx.FL_Shader import FL_Shadertoy
201
+ from .nodes.vfx.FL_TextOverlay import FL_TextOverlayNode
202
+
203
+ # VIDEO NODES
204
+ from .nodes.video.FL_FILM import FL_FILM
205
+ from .nodes.video.FL_ProResVideo import FL_ProResVideo
206
+ from .nodes.video.FL_RIFE import FL_RIFE
207
+ from .nodes.video.FL_VideoBatchSplitter import FL_VideoBatchSplitter
208
+ from .nodes.video.FL_VideoCadence import FL_VideoCadence
209
+ from .nodes.video.FL_VideoCadenceCompile import FL_VideoCadenceCompile
210
+ from .nodes.video.FL_VideoCrossfade import FL_VideoCrossfade
211
+ from .nodes.video.FL_VideoCut import FL_VideoCut
212
+ from .nodes.video.FL_VideoTrim import FL_VideoTrim
213
+
214
+ # WIP NODES
215
+ from .nodes.wip.FL_KsamplerFractals import FL_FractalKSampler
216
+ from .nodes.wip.FL_TimeLine import FL_TimeLine
217
+ from .nodes.wip.FL_WF_Agent import FL_WF_Agent
218
+ from .nodes.wip.FL_WanFirstLastFrameToVideo import FL_WanFirstLastFrameToVideo
219
+ from .nodes.wip.FL_QwenImageEditStrength import FL_QwenImageEditStrength
220
+ from .nodes.wip.FL_WanVaceToVideoMultiRef import FL_WanVaceToVideoMultiRef
221
+ from .nodes.wip.FL_AnimatedShapePatterns import FL_AnimatedShapePatterns
222
+ from .nodes.wip.FL_PathAnimator import FL_PathAnimator
223
+ from .nodes.wip.FL_WanVideoContinue import FL_WanVideoContinue
224
+ from .nodes.wip.FL_WanVideoBlender import FL_WanVideoBlender
225
+ from .nodes.wip.FL_WanVideoBlender3Way import FL_WanVideoBlender3Way
226
+ from .nodes.wip.FL_WanVideoContinuationBlender import FL_WanVideoContinuationBlender
227
+
228
+ NODE_CLASS_MAPPINGS = {
229
+ "FL_SaveWebM": FL_SaveWebM,
230
+ "FL_TextOverlayNode": FL_TextOverlayNode,
231
+ "FL_ImageBlank": FL_ImageBlank,
232
+ "FL_ImageRandomizer": FL_ImageRandomizer,
233
+ "FL_ImageCaptionSaver": FL_ImageCaptionSaver,
234
+ "FL_VideoCaptionSaver": FL_VideoCaptionSaver,
235
+ "FL_ImageDimensionDisplay": FL_ImageDimensionDisplay,
236
+ "FL_GeminiVideoCaptioner": FL_GeminiVideoCaptioner,
237
+ "FL_GeminiImageEditor": FL_GeminiImageEditor,
238
+ "FL_GPT_Image1": FL_GPT_Image1,
239
+ "FL_CodeNode": FL_CodeNode,
240
+ "FL_ImagePixelator": FL_ImagePixelator,
241
+ "FL_ImageAddToBatch": FL_ImageAddToBatch,
242
+ "FL_DirectoryCrawl": FL_DirectoryCrawl,
243
+ "FL_Ascii": FL_Ascii,
244
+ "FL_ReplaceColor": FL_ReplaceColor,
245
+ "FL_ImageAddNoise": FL_ImageAddNoise,
246
+ "FL_WordFrequencyGraph": FL_WordFrequencyGraph,
247
+ "FL_Glitch": FL_Glitch,
248
+ "FL_Ripple": FL_Ripple,
249
+ "FL_PixelSort": FL_PixelSort,
250
+ "FL_HexagonalPattern": FL_HexagonalPattern,
251
+ "FL_NFTGenerator": FL_NFTGenerator,
252
+ "FL_HalftonePattern": FL_HalftonePattern,
253
+ "FL_RandomNumber": FL_RandomNumber,
254
+ "FL_PromptSelector": FL_PromptSelector,
255
+ "FL_Shadertoy": FL_Shadertoy,
256
+ "FL_PixelArtShader": FL_PixelArtShader,
257
+ "FL_InfiniteZoom": FL_InfiniteZoom,
258
+ "FL_PaperDrawn": FL_PaperDrawn,
259
+ "FL_ImageNotes": FL_ImageNotes,
260
+ "FL_ImageCollage": FL_ImageCollage,
261
+ "FL_KsamplerSettings": FL_KsamplerSettings,
262
+ "FL_RetroEffect": FL_RetroEffect,
263
+ "FL_InpaintCrop": FL_InpaintCrop,
264
+ "FL_Inpaint_Stitch": FL_Inpaint_Stitch,
265
+ "FL_SDUltimate_Slices": FL_SDUltimate_Slices,
266
+ "FL_BatchAlign": FL_BatchAlign,
267
+ "FL_VideoRecompose": FL_VideoRecompose,
268
+ "FL_VideoCropMask": FL_VideoCropMask,
269
+ "FL_SeparateMaskComponents": FL_SeparateMaskComponents,
270
+ "FL_PasteOnCanvas": FL_PasteOnCanvas,
271
+ "FL_BulletHellGame": FL_BulletHellGame,
272
+ "FL_TetrisGame": FL_TetrisGame,
273
+ "FL_Dither": FL_Dither,
274
+ "FL_SystemCheck": FL_SystemCheck,
275
+ "FL_ColorPicker": FL_ColorPicker,
276
+ "FL_GradGenerator": FL_GradGenerator,
277
+ "FL_MirrorAndAppendCaptions": FL_MirrorAndAppendCaptions,
278
+ "FL_ImageCaptionLayout": FL_ImageCaptionLayout,
279
+ "FL_HFHubModelUploader": FL_HFHubModelUploader,
280
+ "FL_ZipDirectory": FL_ZipDirectory,
281
+ "FL_ZipSave": FL_ZipSave,
282
+ "FL_GPT_Vision": FL_GPT_Vision,
283
+ "FL_TimeLine": FL_TimeLine,
284
+ "FL_SimpleGPTVision": FL_SimpleGPTVision,
285
+ "FL_SendToDiscordWebhook": FL_SendToDiscordWebhook,
286
+ "FL_HF_Character": FL_HF_Character,
287
+ "FL_CaptionToCSV": FL_CaptionToCSV,
288
+ "FL_KsamplerPlus": FL_KsamplerPlus,
289
+ "FL_KsamplerPlusV2": FL_KsamplerPlusV2,
290
+ "FL_KsamplerBasic": FL_KsamplerBasic,
291
+ "FL_FractalKSampler": FL_FractalKSampler,
292
+ "FL_UpscaleModel": FL_UpscaleModel,
293
+ "FL_SaveCSV": FL_SaveCSV,
294
+ "FL_LoadCSV": FL_LoadCSV,
295
+ "FL_CSVExtractor": FL_CSVExtractor,
296
+ "FL_KSamplerXYZPlot": FL_KSamplerXYZPlot,
297
+ "FL_SamplerStrings": FL_SamplerStrings,
298
+ "FL_SchedulerStrings": FL_SchedulerStrings,
299
+ "FL_ImageCaptionLayoutPDF": FL_ImageCaptionLayoutPDF,
300
+ "FL_Dalle3": FL_Dalle3,
301
+ "FL_SaveImages": FL_SaveImages,
302
+ "FL_LoadImage": FL_LoadImage,
303
+ "FL_PDFLoader": FL_PDFLoader,
304
+ "FL_PDFToImages": FL_PDFToImages,
305
+ "FL_PDFSaver": FL_PDFSaver,
306
+ "FL_ImagesToPDF": FL_ImagesToPDF,
307
+ "FL_PDFMerger": FL_PDFMerger,
308
+ "FL_PDFTextExtractor": FL_PDFTextExtractor,
309
+ "FL_PDFImageExtractor": FL_PDFImageExtractor,
310
+ "FL_BulkPDFLoader": FL_BulkPDFLoader,
311
+ "FL_TextToPDF": FL_TextToPDF,
312
+ "FL_PDFEncryptor": FL_PDFEncryptor,
313
+ "FL_SaveAndDisplayImage": FL_SaveAndDisplayImage,
314
+ "FL_OllamaCaptioner": FL_OllamaCaptioner,
315
+ "FL_ImageAdjuster": FL_ImageAdjuster,
316
+ "FL_CaptionSaver_V2": FL_CaptionSaver_V2,
317
+ "FL_PathTypeChecker": FL_PathTypeChecker,
318
+ "FL_SaveWebPImage(SaveImage)": FL_SaveWebPImage,
319
+ "FL_MadLibGenerator": FL_MadLibGenerator,
320
+ "FL_Math": FL_Math,
321
+ "FL_ImageSlicer": FL_ImageSlicer,
322
+ "FL_ImageSelector": FL_ImageSelector,
323
+ "FL_ImagePicker": FL_ImagePicker,
324
+ "FL_ImageOverlay": FL_ImageOverlay,
325
+ "FL_ImageAspectCropper": FL_ImageAspectCropper,
326
+ "FL_HF_UploaderAbsolute": FL_HF_UploaderAbsolute,
327
+ "FL_ImageListToImageBatch": FL_ImageListToImageBatch,
328
+ "FL_ImageBatchToImageList": FL_ImageBatchToImageList,
329
+ "FL_ImageBatchToGrid": FL_ImageBatchToGrid,
330
+ "FL_ApplyMask": FL_ApplyMask,
331
+ "FL_ProResVideo": FL_ProResVideo,
332
+ "FL_Padding": FL_Padding,
333
+ "FL_GoogleDriveDownloader": FL_GoogleDriveDownloader,
334
+ "FL_NodeLoader": FL_NodeLoader,
335
+ "FL_NodePackLoader": FL_NodePackLoader,
336
+ "FL_API_Base64_ImageLoader": FL_API_Base64_ImageLoader,
337
+ "FL_API_ImageSaver": FL_API_ImageSaver,
338
+ "FL_GoogleDriveImageDownloader": FL_GoogleDriveImageDownloader,
339
+ "FL_AnimeLineExtractor": FL_AnimeLineExtractor,
340
+ "FL_ClipScanner": FL_ClipScanner,
341
+ "FL_VideoCut": FL_VideoCut,
342
+ "FL_GeminiTextAPI": FL_GeminiTextAPI,
343
+ "FL_JS": FL_JS,
344
+ "FL_HFDatasetDownloader": FL_HFDatasetDownloader,
345
+ "FL_WF_Agent": FL_WF_Agent,
346
+ "FL_BlackFrameReject": FL_BlackFrameReject,
347
+ "FL_PixVerseAPI": FL_PixVerseAPI,
348
+ "FL_Fal_Pixverse": FL_Fal_Pixverse,
349
+ "FL_Fal_Kontext": FL_Fal_Kontext,
350
+ "FL_Fal_Gemini_ImageEdit": FL_Fal_Gemini_ImageEdit,
351
+ "FL_Fal_Seedance_i2v": FL_Fal_Seedance_i2v,
352
+ "FL_Fal_Seedream_Edit": FL_Fal_Seedream_Edit,
353
+ "FL_Fal_SeedVR_Upscale": FL_Fal_SeedVR_Upscale,
354
+ "FL_Fal_Pixverse_Transition": FL_Fal_Pixverse_Transition,
355
+ "FL_Fal_Pixverse_LipSync": FL_Fal_Pixverse_LipSync,
356
+ "FL_Fal_Kling_AIAvatar": FL_Fal_Kling_AIAvatar,
357
+ "FL_Fal_Sora": FL_Fal_Sora,
358
+ "FL_PromptBasic": FL_PromptBasic,
359
+ "FL_PromptMulti": FL_PromptMulti,
360
+ "FL_PromptSelectorBasic": FL_PromptSelectorBasic,
361
+ "FL_PaddingRemover": FL_PaddingRemover,
362
+ "FL_GPT_Text": FL_GPT_Text,
363
+ "FL_GoogleCloudStorage": FL_GoogleCloudStorage,
364
+ "FL_Switch": FL_Switch,
365
+ "FL_Switch_Big": FL_Switch_Big,
366
+ "FL_PasteByMask": FL_PasteByMask,
367
+ "FL_ModelInspector": FL_ModelInspector,
368
+ "FL_Float": FL_Float,
369
+ "FL_UnloadModel": FL_UnloadModel,
370
+ "FL_UnloadAllModels": FL_UnloadAllModels,
371
+ "FL_VideoTrim": FL_VideoTrim,
372
+ "FL_VideoBatchSplitter": FL_VideoBatchSplitter,
373
+ "FL_VideoCrossfade": FL_VideoCrossfade,
374
+ "FL_VideoCadence": FL_VideoCadence,
375
+ "FL_VideoCadenceCompile": FL_VideoCadenceCompile,
376
+ "FL_WanVaceToVideoMultiRef": FL_WanVaceToVideoMultiRef,
377
+ "FL_RIFE": FL_RIFE,
378
+ "FL_FILM": FL_FILM,
379
+ "FL_GeminiImageGenADV": FL_GeminiImageGenADV,
380
+ "FL_GPT_Image1_ADV": FL_GPT_Image1_ADV,
381
+ "FL_ImageBatch": FL_ImageBatch,
382
+ "FL_Hedra_API": FL_Hedra_API,
383
+ "FL_RunwayImageAPI": FL_RunwayImageAPI,
384
+ "FL_RunwayAct2": FL_RunwayAct2,
385
+ "FL_ImageCrop": FL_ImageCrop,
386
+ "FL_WanFirstLastFrameToVideo": FL_WanFirstLastFrameToVideo,
387
+ "FL_WanVideoContinue": FL_WanVideoContinue,
388
+ "FL_WanVideoBlender": FL_WanVideoBlender,
389
+ "FL_WanVideoBlender3Way": FL_WanVideoBlender3Way,
390
+ "FL_WanVideoContinuationBlender": FL_WanVideoContinuationBlender,
391
+ "FL_Veo3VideoGen": FL_Veo3VideoGen,
392
+ "FL_VertexGemini25FlashImage": FL_VertexGemini25FlashImage,
393
+ "FL_SaveRGBAAnimatedWebP": FL_SaveRGBAAnimatedWebP,
394
+ "FL_Audio_BPM_Analyzer": FL_Audio_BPM_Analyzer,
395
+ "FL_Audio_Beat_Visualizer": FL_Audio_Beat_Visualizer,
396
+ "FL_Audio_Crop": FL_Audio_Crop,
397
+ "FL_Audio_Drum_Detector": FL_Audio_Drum_Detector,
398
+ "FL_Audio_Envelope_Visualizer": FL_Audio_Envelope_Visualizer,
399
+ "FL_Audio_Music_Video_Sequencer": FL_Audio_Music_Video_Sequencer,
400
+ "FL_Audio_Reactive_Brightness": FL_Audio_Reactive_Brightness,
401
+ "FL_Audio_Reactive_Edge_Glow": FL_Audio_Reactive_Edge_Glow,
402
+ "FL_Audio_Reactive_Envelope": FL_Audio_Reactive_Envelope,
403
+ "FL_Audio_Reactive_Saturation": FL_Audio_Reactive_Saturation,
404
+ "FL_Audio_Reactive_Scale": FL_Audio_Reactive_Scale,
405
+ "FL_Audio_Reactive_Speed": FL_Audio_Reactive_Speed,
406
+ "FL_Audio_Segment_Extractor": FL_Audio_Segment_Extractor,
407
+ "FL_Audio_Separation": FL_Audio_Separation,
408
+ "FL_Audio_Shot_Iterator": FL_Audio_Shot_Iterator,
409
+ "FL_QwenImageEditStrength": FL_QwenImageEditStrength,
410
+ "FL_IntToFloat": FL_IntToFloat,
411
+ "FL_FloatToInt": FL_FloatToInt,
412
+ "FL_AnimatedShapePatterns": FL_AnimatedShapePatterns,
413
+ "FL_PathAnimator": FL_PathAnimator,
414
+ "FL_RandomShapeGenerator": FL_RandomShapeGenerator,
415
+ "FL_KartelJobInput": FL_KartelJobInput,
416
+ "FL_KartelJobOutput": FL_KartelJobOutput,
417
+ }
418
+
419
+ NODE_DISPLAY_NAME_MAPPINGS = {
420
+ "FL_ImageBlank": "FL Image Blank",
421
+ "FL_ImageRandomizer": "FL Image Randomizer",
422
+ "FL_ImageCaptionSaver": "FL Image Caption Saver",
423
+ "FL_VideoCaptionSaver": "FL Video Caption Saver",
424
+ "FL_ImageDimensionDisplay": "FL Image Size",
425
+ "FL_GeminiVideoCaptioner": "FL Gemini Video Captioner",
426
+ "FL_GeminiImageEditor": "FL Gemini Image Editor",
427
+ "FL_GPT_Image1": "FL GPT Image-1",
428
+ "FL_CodeNode": "FL Code Node",
429
+ "FL_ImagePixelator": "FL Image Pixelator",
430
+ "FL_ImageAddToBatch": "FL Image Add To Batch",
431
+ "FL_DirectoryCrawl": "FL Directory Crawl",
432
+ "FL_Ascii": "FL Ascii",
433
+ "FL_ReplaceColor": "FL Replace Color",
434
+ "FL_ImageAddNoise": "FL Image Add Noise",
435
+ "FL_WordFrequencyGraph": "FL Word Frequency Graph",
436
+ "FL_Glitch": "FL Glitch",
437
+ "FL_Ripple": "FL Ripple",
438
+ "FL_PixelSort": "FL PixelSort",
439
+ "FL_HexagonalPattern": "FL Hexagonal Pattern",
440
+ "FL_NFTGenerator": "FL NFT Generator",
441
+ "FL_HalftonePattern": "FL Halftone",
442
+ "FL_RandomNumber": "FL Random Number",
443
+ "FL_PromptSelector": "FL Prompt Selector",
444
+ "FL_PromptSelectorBasic": "FL Prompt Selector Basic",
445
+ "FL_Shadertoy": "FL Shadertoy",
446
+ "FL_PixelArtShader": "FL Pixel Art",
447
+ "FL_InfiniteZoom": "FL Infinite Zoom",
448
+ "FL_PaperDrawn": "FL Paper Drawn",
449
+ "FL_ImageNotes": "FL Image Notes",
450
+ "FL_ImageCollage": "FL Image Collage",
451
+ "FL_KsamplerSettings": "FL KSampler Settings",
452
+ "FL_RetroEffect": "FL Retro Effect",
453
+ "FL_InpaintCrop": "FL Inpaint Crop",
454
+ "FL_Inpaint_Stitch": "FL Inpaint Stitch",
455
+ "FL_SDUltimate_Slices": "FL SDUltimate Slices",
456
+ "FL_BatchAlign": "FL Batch Align",
457
+ "FL_VideoCropMask": "FL Video CropMask",
458
+ "FL_VideoRecompose": "FL Video Recompose",
459
+ "FL_SeparateMaskComponents": "FL Separate Mask Components",
460
+ "FL_PasteOnCanvas": "FL Paste On Canvas",
461
+ "FL_BulletHellGame": "FL BulletHell Game",
462
+ "FL_TetrisGame": "FL Tetris Game",
463
+ "FL_Dither": "FL Dither",
464
+ "FL_SystemCheck": "FL System Check",
465
+ "FL_ColorPicker": "FL Color Picker",
466
+ "FL_GradGenerator": "FL Grad Generator",
467
+ "FL_MirrorAndAppendCaptions": "FL Mirror And Append Captions",
468
+ "FL_ImageCaptionLayout": "FL Image Caption Layout",
469
+ "FL_HFHubModelUploader": "FL HFHub Model Uploader",
470
+ "FL_ZipDirectory": "FL Zip Directory",
471
+ "FL_ZipSave": "FL_ZipSave",
472
+ "FL_GPT_Vision": "FL GPT Captions",
473
+ "FL_TimeLine": "FL Time Line",
474
+ "FL_SimpleGPTVision": "FL Simple GPT Vision",
475
+ "FL_SendToDiscordWebhook": "FL Kytra Discord Webhook",
476
+ "FL_HF_Character": "FL HF Character",
477
+ "FL_CaptionToCSV": "FL Caption To CSV",
478
+ "FL_KsamplerPlus": "FL KSampler Plus",
479
+ "FL_KsamplerPlusV2": "FL KSampler Plus V2",
480
+ "FL_KsamplerBasic": "FL KSampler Basic",
481
+ "FL_FractalKSampler": "FL Fractal KSampler",
482
+ "FL_UpscaleModel": "FL Upscale Model",
483
+ "FL_SaveCSV": "FL Save CSV",
484
+ "FL_LoadCSV": "FL Load CSV",
485
+ "FL_CSVExtractor": "FL CSV Extractor",
486
+ "FL_KSamplerXYZPlot": "FL KSampler XYZ Plot",
487
+ "FL_SamplerStrings": "FL Sampler String XYZ",
488
+ "FL_SchedulerStrings": "FL Scheduler String XYZ",
489
+ "FL_ImageCaptionLayoutPDF": "FL Image Caption Layout PDF",
490
+ "FL_Dalle3": "FL Dalle 3",
491
+ "FL_SaveImages": "FL Save Images",
492
+ "FL_LoadImage": "FL Load Image",
493
+ "FL_PDFLoader": "FL PDF Loader",
494
+ "FL_PDFToImages": "FL PDF To Images",
495
+ "FL_PDFSaver": "FL PDF Saver",
496
+ "FL_ImagesToPDF": "FL Images To PDF",
497
+ "FL_PDFMerger": "FL PDF Merger",
498
+ "FL_PDFTextExtractor": "FL PDF Text Extractor",
499
+ "FL_PDFImageExtractor": "FL PDF Image Extractor",
500
+ "FL_BulkPDFLoader": "FL Bulk PDF Loader",
501
+ "FL_TextToPDF": "FL Text To PDF",
502
+ "FL_PDFEncryptor": "FL PDF Encryptor",
503
+ "FL_SaveAndDisplayImage": "FL Save And Display Image",
504
+ "FL_OllamaCaptioner": "FL Ollama Captioner by Cosmic",
505
+ "FL_ImageAdjuster": "FL Image Adjuster",
506
+ "FL_CaptionSaver_V2": "FL Caption Saver V2",
507
+ "FL_PathTypeChecker": "FL Path Type Checker",
508
+ "FL_SaveWebPImage(SaveImage)": "FL Save WebP Image",
509
+ "FL_MadLibGenerator": "FL MadLib Generator",
510
+ "FL_Math": "FL Math",
511
+ "FL_ImageSlicer": "FL Image Slicer",
512
+ "FL_ImageSelector": "FL Image Selector",
513
+ "FL_ImagePicker": "FL Image Picker",
514
+ "FL_ImageOverlay": "FL Image Overlay",
515
+ "FL_ImageAspectCropper": "FL Image Aspect Cropper",
516
+ "FL_HF_UploaderAbsolute": "FL HF Uploader Absolute",
517
+ "FL_ImageListToImageBatch": "FL Image List To Image Batch",
518
+ "FL_ImageBatchToImageList": "FL Image Batch To Image List",
519
+ "FL_ImageBatchToGrid": "FL Image Batch To Grid",
520
+ "FL_ApplyMask": "FL Apply Mask",
521
+ "FL_ProResVideo": "FL ProRes Video",
522
+ "FL_Padding": "FL Padding",
523
+ "FL_GoogleDriveDownloader": "FL Google Drive Downloader",
524
+ "FL_NodeLoader": "FL Node Loader",
525
+ "FL_NodePackLoader": "FL Node Pack Loader",
526
+ "FL_API_Base64_ImageLoader": "FL API Base64 Image Loader",
527
+ "FL_API_ImageSaver": "FL API Image Saver",
528
+ "FL_GoogleDriveImageDownloader": "FL Google Drive Image Downloader",
529
+ "FL_AnimeLineExtractor": "FL Anime Line Extractor",
530
+ "FL_ClipScanner": "FL Clip Scanner (Kytra)",
531
+ "FL_VideoCut": "FL Video Cut Detector",
532
+ "FL_GeminiTextAPI": "FL Gemini Text API",
533
+ "FL_JS": "FL JavaScript",
534
+ "FL_HFDatasetDownloader": "FL HF Dataset Downloader",
535
+ "FL_WF_Agent": "FL Workflow Agent",
536
+ "FL_BlackFrameReject": "FL Black Frame Reject",
537
+ "FL_PixVerseAPI": "FL PixVerse API",
538
+ "FL_Fal_Pixverse": "FL Fal Pixverse API",
539
+ "FL_Fal_Kontext": "FL Fal Kontext API",
540
+ "FL_Fal_Gemini_ImageEdit": "FL Fal Gemini Image Edit",
541
+ "FL_Fal_Seedance_i2v": "FL Fal Seedance i2v",
542
+ "FL_Fal_Seedream_Edit": "FL Fal Seedream Edit",
543
+ "FL_Fal_SeedVR_Upscale": "FL Fal SeedVR Upscale",
544
+ "FL_Fal_Pixverse_Transition": "FL Fal Pixverse Transition",
545
+ "FL_Fal_Pixverse_LipSync": "FL Fal Pixverse LipSync",
546
+ "FL_Fal_Kling_AIAvatar": "FL Fal Kling AI Avatar",
547
+ "FL_Fal_Sora": "FL Fal Sora 2",
548
+ "FL_PromptBasic": "FL Prompt Basic",
549
+ "FL_PromptMulti": "FL Prompt Multi",
550
+ "FL_PromptSelectorBasic": "FL Prompt Selector Basic",
551
+ "FL_PaddingRemover": "FL Padding Remover",
552
+ "FL_GPT_Text": "FL GPT Text",
553
+ "FL_GoogleCloudStorage": "FL Google Cloud Storage Uploader",
554
+ "FL_Switch": "FL Switch",
555
+ "FL_Switch_Big": "FL Switch Big",
556
+ "FL_PasteByMask": "FL Paste By Mask",
557
+ "FL_Float": "FL Float",
558
+ "FL_UnloadModel": "FL Unload Model",
559
+ "FL_UnloadAllModels": "FL Unload All Models",
560
+ "FL_ModelInspector": "FL Model Inspector",
561
+ "FL_VideoTrim": "FL Video Trim",
562
+ "FL_VideoBatchSplitter": "FL Video Batch Splitter",
563
+ "FL_VideoCrossfade": "FL Video Crossfade",
564
+ "FL_VideoCadence": "FL Video Cadence",
565
+ "FL_WanVaceToVideoMultiRef": "FL Wan Vace To Video Multi Reference",
566
+ "FL_VideoCadenceCompile": "FL Video Cadence Compile",
567
+ "FL_FILM": "FL FILM Frame Interpolation",
568
+ "FL_RIFE": "FL RIFE Frame Interpolation",
569
+ "FL_GeminiImageGenADV": "FL Gemini Image Gen ADV",
570
+ "FL_GPT_Image1_ADV": "FL GPT Image1 ADV",
571
+ "FL_ImageBatch": "FL Image Batch",
572
+ "FL_Hedra_API": "FL Hedra API",
573
+ "FL_RunwayImageAPI": "FL Runway Image API",
574
+ "FL_RunwayAct2": "FL Runway Act2",
575
+ "FL_TextOverlayNode": "FL Text Overlay",
576
+ "FL_SaveWebM": "FL Save WebM",
577
+ "FL_ImageCrop": "FL Image Crop",
578
+ "FL_WanFirstLastFrameToVideo": "FL Wan First Frame Last Frame",
579
+ "FL_WanVideoContinue": "FL Wan Video Continue",
580
+ "FL_WanVideoBlender": "FL Wan Video Blender",
581
+ "FL_WanVideoBlender3Way": "FL Wan Video Blender 3-Way",
582
+ "FL_WanVideoContinuationBlender": "FL Wan Video Continuation Blender",
583
+ "FL_Veo3VideoGen": "FL Vertex Veo3",
584
+ "FL_VertexGemini25FlashImage": "FL Vertex Gemini 2.5 Flash Image",
585
+ "FL_SaveRGBAAnimatedWebP": "FL Save RGBA Animated WebP",
586
+ "FL_Audio_BPM_Analyzer": "FL Audio BPM Analyzer",
587
+ "FL_Audio_Beat_Visualizer": "FL Audio Beat Visualizer",
588
+ "FL_Audio_Crop": "FL Audio Crop",
589
+ "FL_Audio_Drum_Detector": "FL Audio Drum Detector",
590
+ "FL_Audio_Envelope_Visualizer": "FL Audio Envelope Visualizer",
591
+ "FL_Audio_Music_Video_Sequencer": "FL Audio Music Video Sequencer",
592
+ "FL_Audio_Reactive_Brightness": "FL Audio Reactive Brightness",
593
+ "FL_Audio_Reactive_Edge_Glow": "FL Audio Reactive Edge Glow",
594
+ "FL_Audio_Reactive_Envelope": "FL Audio Reactive Envelope",
595
+ "FL_Audio_Reactive_Saturation": "FL Audio Reactive Saturation",
596
+ "FL_Audio_Reactive_Scale": "FL Audio Reactive Scale",
597
+ "FL_Audio_Reactive_Speed": "FL Audio Reactive Speed",
598
+ "FL_Audio_Segment_Extractor": "FL Audio Segment Extractor",
599
+ "FL_Audio_Separation": "FL Audio Separation",
600
+ "FL_Audio_Shot_Iterator": "FL Audio Shot Iterator",
601
+ "FL_QwenImageEditStrength": "FL Qwen Image Edit with Strength",
602
+ "FL_IntToFloat": "FL Int to Float",
603
+ "FL_FloatToInt": "FL Float to Int",
604
+ "FL_AnimatedShapePatterns": "FL Animated Shape Patterns",
605
+ "FL_PathAnimator": "FL Path Animator",
606
+ "FL_RandomShapeGenerator": "FL Random Shape Generator",
607
+ "FL_KartelJobInput": "FL Kartel Job Input",
608
+ "FL_KartelJobOutput": "FL Kartel Job Output",
609
+ }
610
+
611
+
612
+ ascii_art = """
613
+
614
+ ███╗ ███╗ █████╗ ██████╗██╗ ██╗██╗███╗ ██╗███████╗
615
+ ████╗ ████║██╔══██╗██╔════╝██║ ██║██║████╗ ██║██╔════╝
616
+ ██╔████╔██║███████║██║ ███████║██║██╔██╗ ██║█████╗
617
+ ██║╚██╔╝██║██╔══██║██║ ██╔══██║██║██║╚██╗██║██╔══╝
618
+ ██║ ╚═╝ ██║██║ ██║╚██████╗██║ ██║██║██║ ╚████║███████╗
619
+ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝╚══════╝
620
+
621
+ ██████╗ ███████╗██╗ ██╗ ██╗███████╗██╗ ██████╗ ███╗ ██╗███████╗
622
+ ██╔══██╗██╔════╝██║ ██║ ██║██╔════╝██║██╔═══██╗████╗ ██║██╔════╝
623
+ ██║ ██║█████╗ ██║ ██║ ██║███████╗██║██║ ██║██╔██╗ ██║███████╗
624
+ ██║ ██║██╔══╝ ██║ ██║ ██║╚════██║██║██║ ██║██║╚██╗██║╚════██║
625
+ ██████╔╝███████╗███████╗╚██████╔╝███████║██║╚██████╔╝██║ ╚████║███████║
626
+ ╚═════╝ ╚══════╝╚══════╝ ╚═════╝ ╚══════╝╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝
627
+
628
+
629
+ """
630
+ print(ascii_art)
631
+
632
+ # Using OpenCV for video processing
633
+
634
+ WEB_DIRECTORY = "./web"
635
+ __all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]
custom_nodes/ComfyUI_Fill-Nodes/fonts/Barcode.ttf ADDED
Binary file (37.3 kB). View file
 
custom_nodes/ComfyUI_Fill-Nodes/fonts/Circles.ttf ADDED
Binary file (21.3 kB). View file
 
custom_nodes/ComfyUI_Fill-Nodes/fonts/Fancy.otf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:628e355f6da4ab4b4ae92005b44d7d69082bdf6ba3c2d726e66edfba75169b8c
3
+ size 163536
custom_nodes/ComfyUI_Fill-Nodes/fonts/Pattern.otf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8f72351fa99ea69b1a67642ed7ef196330252ce9114eaa95e36721ab02ffcdc8
3
+ size 123064
custom_nodes/ComfyUI_Fill-Nodes/fonts/Square.TTF ADDED
Binary file (28.8 kB). View file
 
custom_nodes/ComfyUI_Fill-Nodes/fonts/arial.ttf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:413c78f91bd39e134f3c0bb204b1d5a90f29df9efddc8fd26950a178058d5d74
3
+ size 367112
custom_nodes/ComfyUI_Fill-Nodes/images/.DS_Store ADDED
Binary file (6.15 kB). View file
 
custom_nodes/ComfyUI_Fill-Nodes/images/nodes/HF.png ADDED

Git LFS Details

  • SHA256: 9b6cc46a619c3221111794be6d4973cc0253361860446b4b9445151b438b7349
  • Pointer size: 131 Bytes
  • Size of remote file: 213 kB
custom_nodes/ComfyUI_Fill-Nodes/images/nodes/Patreon.png ADDED

Git LFS Details

  • SHA256: a231f817e0b5454fdc47cfdc85371bdc62c899eeeeba98067018b34c6d4180d9
  • Pointer size: 131 Bytes
  • Size of remote file: 599 kB
custom_nodes/ComfyUI_Fill-Nodes/images/nodes/Utility_nodes.png ADDED

Git LFS Details

  • SHA256: ef617fdf44602af45104b19c446e4555c7dddea14407e890cac2a175cc61ff32
  • Pointer size: 131 Bytes
  • Size of remote file: 276 kB
custom_nodes/ComfyUI_Fill-Nodes/images/nodes/VFX_nodes.png ADDED

Git LFS Details

  • SHA256: 1ecb3654f9659a4d41ea6f131f720229865ab444a555107d0989e30ba759d4df
  • Pointer size: 131 Bytes
  • Size of remote file: 361 kB
custom_nodes/ComfyUI_Fill-Nodes/images/nodes/ai.png ADDED

Git LFS Details

  • SHA256: 58ced7290115bced3112e81dac4ff13e2fefca6d47453c4dd9f29b42a97dfa78
  • Pointer size: 130 Bytes
  • Size of remote file: 77.7 kB
custom_nodes/ComfyUI_Fill-Nodes/images/nodes/api.png ADDED

Git LFS Details

  • SHA256: 7aa4db72e09313a1e6885fe04e8eb609a6e5ebd226f2c89ab3182ec515811dd5
  • Pointer size: 131 Bytes
  • Size of remote file: 106 kB
custom_nodes/ComfyUI_Fill-Nodes/images/nodes/captioning_nodes.png ADDED

Git LFS Details

  • SHA256: cddbc5d13d374c4a027a7dd08aaffe63b7f66f92baf77c0c209a3aa4c34fee05
  • Pointer size: 131 Bytes
  • Size of remote file: 256 kB
custom_nodes/ComfyUI_Fill-Nodes/images/nodes/clip.png ADDED

Git LFS Details

  • SHA256: 1e208182f9d8d92553bae0daf2484a1033c8943882e8e42c7ecbdb631493d1f6
  • Pointer size: 130 Bytes
  • Size of remote file: 29 kB
custom_nodes/ComfyUI_Fill-Nodes/images/nodes/discord.png ADDED

Git LFS Details

  • SHA256: ca2399bc2f3ea489b446b674c49a5be2d4816e9559563d678e7907ff870c5113
  • Pointer size: 130 Bytes
  • Size of remote file: 43.5 kB
custom_nodes/ComfyUI_Fill-Nodes/images/nodes/experimental.png ADDED

Git LFS Details

  • SHA256: 628c878af2fb9d419a709b800c1cd6c7d386abc24a1f826703a9772466505da2
  • Pointer size: 131 Bytes
  • Size of remote file: 110 kB
custom_nodes/ComfyUI_Fill-Nodes/images/nodes/games.png ADDED

Git LFS Details

  • SHA256: ebca9ec24d00bad129e5f19b53063b06a7d530a7b6d222a5b8c1f37844b8f67c
  • Pointer size: 130 Bytes
  • Size of remote file: 76.6 kB
custom_nodes/ComfyUI_Fill-Nodes/images/nodes/googledrive.png ADDED

Git LFS Details

  • SHA256: 177de11fccf95489d8c24118780e7ee692e7a2306263792eb06de48552e9e600
  • Pointer size: 130 Bytes
  • Size of remote file: 50.3 kB
custom_nodes/ComfyUI_Fill-Nodes/images/nodes/gpt_nodes.png ADDED

Git LFS Details

  • SHA256: 64869437163d4c11d2693fc86309b1e7d5bc4d49ea2e417ffa17131b5aeea144
  • Pointer size: 131 Bytes
  • Size of remote file: 177 kB
custom_nodes/ComfyUI_Fill-Nodes/images/nodes/images_nodes.png ADDED

Git LFS Details

  • SHA256: 93b14b072a35d1e4f2444b9a384b9db0fe6badc57a34216bbdeae83812c626b5
  • Pointer size: 131 Bytes
  • Size of remote file: 399 kB
custom_nodes/ComfyUI_Fill-Nodes/images/nodes/ksampler_nodes.png ADDED

Git LFS Details

  • SHA256: 5ecfd510911d0b906959c61d8c79756c006e2f16640ab94104e5486b125f5b31
  • Pointer size: 131 Bytes
  • Size of remote file: 345 kB
custom_nodes/ComfyUI_Fill-Nodes/images/nodes/loaders.png ADDED

Git LFS Details

  • SHA256: 31b2f3de413fb750d6ce2ca0857ca9178ffb2f31af1e77d7091e77aaa4121286
  • Pointer size: 131 Bytes
  • Size of remote file: 103 kB
custom_nodes/ComfyUI_Fill-Nodes/images/nodes/math.png ADDED

Git LFS Details

  • SHA256: 98ad2c9a7e80793912e19ae2a340aa19c5933c96842a48007eb1e3ad75602732
  • Pointer size: 130 Bytes
  • Size of remote file: 26.3 kB