MarkLilly commited on
Commit
64896e9
·
verified ·
1 Parent(s): b153144

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. ComfyUI-GGUF/.github/workflows/registry.yaml +21 -0
  2. ComfyUI-GGUF/.gitignore +167 -0
  3. ComfyUI-GGUF/.tracking +17 -0
  4. ComfyUI-GGUF/LICENSE +201 -0
  5. ComfyUI-GGUF/README.md +49 -0
  6. ComfyUI-GGUF/__init__.py +9 -0
  7. ComfyUI-GGUF/__pycache__/__init__.cpython-310.pyc +0 -0
  8. ComfyUI-GGUF/__pycache__/dequant.cpython-310.pyc +0 -0
  9. ComfyUI-GGUF/__pycache__/loader.cpython-310.pyc +0 -0
  10. ComfyUI-GGUF/__pycache__/nodes.cpython-310.pyc +0 -0
  11. ComfyUI-GGUF/__pycache__/ops.cpython-310.pyc +0 -0
  12. ComfyUI-GGUF/dequant.py +301 -0
  13. ComfyUI-GGUF/loader.py +506 -0
  14. ComfyUI-GGUF/nodes.py +329 -0
  15. ComfyUI-GGUF/ops.py +281 -0
  16. ComfyUI-GGUF/pyproject.toml +14 -0
  17. ComfyUI-GGUF/requirements.txt +5 -0
  18. ComfyUI-GGUF/tools/README.md +93 -0
  19. ComfyUI-GGUF/tools/convert.py +365 -0
  20. ComfyUI-GGUF/tools/fix_5d_tensors.py +82 -0
  21. ComfyUI-GGUF/tools/fix_lines_ending.py +31 -0
  22. ComfyUI-GGUF/tools/lcpp.patch +451 -0
  23. ComfyUI-GGUF/tools/read_tensors.py +21 -0
  24. ComfyUI-Jjk-Nodes/LICENSE +21 -0
  25. ComfyUI-Jjk-Nodes/README.md +4 -0
  26. ComfyUI-Jjk-Nodes/__init__.py +27 -0
  27. ComfyUI-Jjk-Nodes/__pycache__/__init__.cpython-310.pyc +0 -0
  28. ComfyUI-Jjk-Nodes/__pycache__/jjk_util.cpython-310.pyc +0 -0
  29. ComfyUI-Jjk-Nodes/jjk_util.py +179 -0
  30. ComfyUI-Jjk-Nodes/js/jjkShowText.js +36 -0
  31. ComfyUI-JoyCaption/.github/workflows/publish.yml +25 -0
  32. ComfyUI-JoyCaption/.tracking +36 -0
  33. ComfyUI-JoyCaption/CaptionTools.py +153 -0
  34. ComfyUI-JoyCaption/JC.py +443 -0
  35. ComfyUI-JoyCaption/JC_GGUF.py +388 -0
  36. ComfyUI-JoyCaption/LICENSE +674 -0
  37. ComfyUI-JoyCaption/README.md +334 -0
  38. ComfyUI-JoyCaption/README_ZH.md +300 -0
  39. ComfyUI-JoyCaption/__init__.py +71 -0
  40. ComfyUI-JoyCaption/__pycache__/CaptionTools.cpython-310.pyc +0 -0
  41. ComfyUI-JoyCaption/__pycache__/JC.cpython-310.pyc +0 -0
  42. ComfyUI-JoyCaption/__pycache__/__init__.cpython-310.pyc +0 -0
  43. ComfyUI-JoyCaption/custom_models.md +154 -0
  44. ComfyUI-JoyCaption/custom_models_example.json +29 -0
  45. ComfyUI-JoyCaption/example_workflows/JoyCaption-GGUF.json +345 -0
  46. ComfyUI-JoyCaption/example_workflows/Joycaption_node.json +526 -0
  47. ComfyUI-JoyCaption/example_workflows/batch_image_text_output.jpg +0 -0
  48. ComfyUI-JoyCaption/example_workflows/batch_image_text_output.json +342 -0
  49. ComfyUI-JoyCaption/jc_data.json +325 -0
  50. ComfyUI-JoyCaption/llama_cpp_install/llama_cpp_install.md +83 -0
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 }}
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/
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
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.
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.
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']
ComfyUI-GGUF/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (479 Bytes). View file
 
ComfyUI-GGUF/__pycache__/dequant.cpython-310.pyc ADDED
Binary file (10.3 kB). View file
 
ComfyUI-GGUF/__pycache__/loader.cpython-310.pyc ADDED
Binary file (16 kB). View file
 
ComfyUI-GGUF/__pycache__/nodes.cpython-310.pyc ADDED
Binary file (10.3 kB). View file
 
ComfyUI-GGUF/__pycache__/ops.cpython-310.pyc ADDED
Binary file (10.6 kB). View file
 
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
+ }
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
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
+
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
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 = ""
ComfyUI-GGUF/requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # main
2
+ gguf>=0.13.0
3
+ # optional - tokenizer
4
+ sentencepiece
5
+ protobuf
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.
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
+
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()
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.")
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.
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()
ComfyUI-Jjk-Nodes/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2023 jjkramhoeft
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
ComfyUI-Jjk-Nodes/README.md ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # ComfyUI-Jjk-Nodes
2
+ A set of custom nodes for ComfyUI - focused on text and parameter utility
3
+
4
+ Minimal code to get a few nodes working
ComfyUI-Jjk-Nodes/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+
4
+ from .jjk_util import *
5
+
6
+ # A dictionary that contains all nodes you want to export with their names
7
+ # NOTE: names should be globally unique
8
+ NODE_CLASS_MAPPINGS = {
9
+ "SDXLRecommendedImageSize": SDXLRecommendedImageSize,
10
+ "JjkText": JjkText,
11
+ "JjkShowText": JjkShowText,
12
+ "JjkConcat": JjkConcat,
13
+ }
14
+
15
+ __all__ = ['NODE_CLASS_MAPPINGS']
16
+
17
+ THIS_DIR=os.path.dirname(os.path.abspath(__file__))
18
+ DIR_DEV_JS=os.path.abspath(f'{THIS_DIR}/js')
19
+ DIR_PY=os.path.abspath(f'{THIS_DIR}/py')
20
+ DIR_WEB_JS=os.path.abspath(f'{THIS_DIR}/../../web/extensions/jjk_util')
21
+
22
+ if not os.path.exists(DIR_WEB_JS):
23
+ os.makedirs(DIR_WEB_JS)
24
+
25
+ shutil.copytree(DIR_DEV_JS, DIR_WEB_JS, dirs_exist_ok=True)
26
+
27
+ print("jjk_util loding")
ComfyUI-Jjk-Nodes/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (680 Bytes). View file
 
ComfyUI-Jjk-Nodes/__pycache__/jjk_util.cpython-310.pyc ADDED
Binary file (3.65 kB). View file
 
ComfyUI-Jjk-Nodes/jjk_util.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import nodes
2
+
3
+ """
4
+
5
+
6
+ Simple utility custom nodes for ComfyUI regarding experimentation with SDXL
7
+
8
+ By Jens Jakob Kramhøft
9
+
10
+ Copyright (c) 2023
11
+
12
+ """
13
+
14
+ MANIFEST = {
15
+ "name": "JJKUtil",
16
+ "version": (0,1,1),
17
+ "author": "Jens Jakob Kramhøft",
18
+ "project": "https://github.com/jjkramhoeft/util-nodes-for-comfyui",
19
+ "description": "A small node suite for ComfyUI",
20
+ }
21
+
22
+ #---------------------------------------------------------------------------------------------------------------------------------------------------#
23
+
24
+ class SDXLRecommendedImageSize:
25
+ RESOLUTIONS = ["Cinema (1536x640)", "Widescreen (1344x768)", "Photo (1216x832)", "TV (1152x896)", "Square (1024x1024)"]
26
+ ASPECT = ["Landscape", "Portrait"]
27
+
28
+ @classmethod
29
+ def INPUT_TYPES(s):
30
+ return {"required": {
31
+ "resolution": (SDXLRecommendedImageSize.RESOLUTIONS, {"default": "Square (1024x1024)"}),
32
+ "aspect": (SDXLRecommendedImageSize.ASPECT, {"default": "Portrait"})
33
+ },
34
+ }
35
+
36
+ RETURN_TYPES = ("INT", "INT", )
37
+ RETURN_NAMES = ("width", "height", )
38
+ FUNCTION = "get_value"
39
+
40
+ CATEGORY = "jjk"
41
+
42
+ def get_value(self, resolution, aspect, ):
43
+ if resolution == "Cinema (1536x640)":
44
+ if aspect == "Landscape":
45
+ return (1536, 640)
46
+ else:
47
+ return (640, 1536)
48
+ if resolution == "Widescreen (1344x768)":
49
+ if aspect == "Landscape":
50
+ return (1344, 768)
51
+ else:
52
+ return (768, 1344)
53
+ if resolution == "Photo (1216x832)":
54
+ if aspect == "Landscape":
55
+ return (1216, 832)
56
+ else:
57
+ return (832, 1216)
58
+ if resolution == "TV (1152x896)":
59
+ if aspect == "Landscape":
60
+ return (1152, 896)
61
+ else:
62
+ return (896, 1152)
63
+ if resolution == "Square (1024x1024)":
64
+ return (1024, 1024)
65
+
66
+ #---------------------------------------------------------------------------------------------------------------------------------------------------#
67
+
68
+ class JjkText:
69
+ @classmethod
70
+ def INPUT_TYPES(s):
71
+ return {"required": {"text": ("STRING", {"multiline": True})}}
72
+
73
+ RETURN_TYPES = ("STRING",)
74
+ RETURN_NAMES = ("text",)
75
+ FUNCTION = "get_value"
76
+ CATEGORY = "jjk"
77
+
78
+ def get_value(self, text):
79
+ return (text,)
80
+
81
+ #---------------------------------------------------------------------------------------------------------------------------------------------------#
82
+
83
+ class JjkShowText:
84
+ @classmethod
85
+ def INPUT_TYPES(s):
86
+ return {
87
+ "required": {
88
+ "text": ("STRING", {"forceInput": True}),
89
+ }
90
+ }
91
+
92
+ INPUT_IS_LIST = True
93
+ RETURN_TYPES = ("STRING",)
94
+ RETURN_NAMES = ("text",)
95
+ FUNCTION = "show_value"
96
+ CATEGORY = "jjk"
97
+ OUTPUT_NODE = True
98
+ OUTPUT_IS_LIST = (True,)
99
+
100
+ def show_value(self, text):
101
+ print(f"show text: {text}")
102
+ return {"ui": {"text": text}, "result": (text,)}
103
+
104
+
105
+ #---------------------------------------------------------------------------------------------------------------------------------------------------#
106
+
107
+ class JjkConcat:
108
+ @classmethod
109
+ def INPUT_TYPES(s):
110
+ return {
111
+ "required": {
112
+ "delimmitor": (["none", "space", "comma"],),
113
+ },
114
+ "optional": {
115
+ "text1": ("STRING", {"forceInput": True}),
116
+ "text2": ("STRING", {"forceInput": True}),
117
+ "text3": ("STRING", {"forceInput": True}),
118
+ "text4": ("STRING", {"forceInput": True}),
119
+ "text5": ("STRING", {"forceInput": True}),
120
+ }
121
+ }
122
+
123
+ RETURN_TYPES = ("STRING",)
124
+ RETURN_NAMES = ("text",)
125
+ FUNCTION = "get_value"
126
+ CATEGORY = "jjk"
127
+
128
+ def get_value(self, delimmitor, text1=None, text2=None, text3=None, text4=None, text5=None):
129
+ needdelim = False
130
+ delim = ""
131
+ if delimmitor == "space":
132
+ delim = " "
133
+ if delimmitor == "comma":
134
+ delim = ", "
135
+
136
+ concatenated = ""
137
+
138
+ if text1:
139
+ concatenated = text1
140
+ needdelim = True
141
+
142
+ if text2:
143
+ if needdelim:
144
+ concatenated += delim
145
+ concatenated += text2
146
+ needdelim = True
147
+
148
+ if text3:
149
+ if needdelim:
150
+ concatenated += delim
151
+ concatenated += text3
152
+ needdelim = True
153
+
154
+ if text4:
155
+ if needdelim:
156
+ concatenated += delim
157
+ concatenated += text4
158
+ needdelim = True
159
+
160
+ if text5:
161
+ if needdelim:
162
+ concatenated += delim
163
+ concatenated += text5
164
+ needdelim = True
165
+
166
+ return (concatenated,)
167
+
168
+ #---------------------------------------------------------------------------------------------------------------------------------------------------#
169
+
170
+
171
+
172
+
173
+ # A dictionary that contains the friendly/humanly readable titles for the nodes
174
+ NODE_DISPLAY_NAME_MAPPINGS = {
175
+ "SDXLRecommendedImageSize": "SDXL Recommended image sizes",
176
+ "JjkText": "Text",
177
+ "JjkShowText": "ShowText",
178
+ "JjkConcat": "Concatenate",
179
+ }
ComfyUI-Jjk-Nodes/js/jjkShowText.js ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { app } from "../../scripts/app.js";
2
+ import { ComfyWidgets } from "../../scripts/widgets.js";
3
+
4
+ // Displays input text on a node
5
+
6
+ app.registerExtension({
7
+ name: "jjk_util.JjkShowText",
8
+ async beforeRegisterNodeDef(nodeType, nodeData, app) {
9
+ if (nodeData.name === "JjkShowText") {
10
+ // When the node is executed we will be sent the input text, display this in the widget
11
+ const onExecuted = nodeType.prototype.onExecuted;
12
+ nodeType.prototype.onExecuted = function (message) {
13
+ onExecuted?.apply(this, arguments);
14
+
15
+ if (this.widgets) {
16
+ const pos = this.widgets.findIndex((w) => w.name === "text");
17
+ if (pos !== -1) {
18
+ for (let i = pos; i < this.widgets.length; i++) {
19
+ this.widgets[i].onRemove?.();
20
+ }
21
+ this.widgets.length = pos;
22
+ }
23
+ }
24
+
25
+ for (const list of message.text) {
26
+ const w = ComfyWidgets["STRING"](this, "text", ["STRING", { multiline: true }], app).widget;
27
+ w.inputEl.readOnly = true;
28
+ w.inputEl.style.opacity = 0.6;
29
+ w.value = list;
30
+ }
31
+
32
+ this.onResize?.(this.size);
33
+ };
34
+ }
35
+ },
36
+ });
ComfyUI-JoyCaption/.github/workflows/publish.yml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Publish to Comfy registry
2
+ on:
3
+ workflow_dispatch:
4
+ push:
5
+ branches:
6
+ - main
7
+ paths:
8
+ - "pyproject.toml"
9
+
10
+ permissions:
11
+ issues: write
12
+
13
+ jobs:
14
+ publish-node:
15
+ name: Publish Custom Node to registry
16
+ runs-on: ubuntu-latest
17
+ if: ${{ github.repository_owner == '1038lab' }}
18
+ steps:
19
+ - name: Check out code
20
+ uses: actions/checkout@v4
21
+ - name: Publish Custom Node
22
+ uses: Comfy-Org/publish-node-action@v1
23
+ with:
24
+ ## Add your own personal access token to your Github Repository secrets and reference it here.
25
+ personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }}
ComfyUI-JoyCaption/.tracking ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .github/workflows/publish.yml
2
+ CaptionTools.py
3
+ JC.py
4
+ JC_GGUF.py
5
+ LICENSE
6
+ README.md
7
+ README_ZH.md
8
+ __init__.py
9
+ custom_models.md
10
+ custom_models_example.json
11
+ example_workflows/JoyCaption-GGUF.json
12
+ example_workflows/JoyCaption-GGUF.png
13
+ example_workflows/Joycaption_node.json
14
+ example_workflows/Joycaption_node.png
15
+ example_workflows/batch_image_text_output.jpg
16
+ example_workflows/batch_image_text_output.json
17
+ jc_data.json
18
+ llama_cpp_install/llama_cpp_install.md
19
+ llama_cpp_install/llama_cpp_install.py
20
+ llama_cpp_install/llama_cpp_install_zh.md
21
+ locales/en/main.json
22
+ locales/en/nodeDefs.json
23
+ locales/fr/main.json
24
+ locales/fr/nodeDefs.json
25
+ locales/ja/main.json
26
+ locales/ja/nodeDefs.json
27
+ locales/ko/main.json
28
+ locales/ko/nodeDefs.json
29
+ locales/ru/main.json
30
+ locales/ru/nodeDefs.json
31
+ locales/zh/main.json
32
+ locales/zh/nodeDefs.json
33
+ pyproject.toml
34
+ requirements.txt
35
+ requirements_gguf.txt
36
+ update.md
ComfyUI-JoyCaption/CaptionTools.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pathlib import Path
3
+ import torch
4
+ import numpy as np
5
+ from PIL import Image, ImageOps
6
+
7
+ class ImageBatchPath:
8
+ @classmethod
9
+ def INPUT_TYPES(s):
10
+ return {
11
+ "required": {"image_dir": ("STRING", {"default": "", "multiline": True, "placeholder": "Input directory containing images"})},
12
+ "optional": {
13
+ "batch_size": ("INT", {"default": 0, "min": 0, "step": 1, "tooltip": "Number of images to load (0 = all images)"}),
14
+ "start_from": ("INT", {"default": 1, "min": 1, "step": 1, "tooltip": "Start from Nth image (1 = first image)"}),
15
+ "sort_method": (["sequential", "reverse", "random"], {"default": "sequential", "tooltip": "Image loading order: sequential/reverse/random"})
16
+ }
17
+ }
18
+
19
+ RETURN_TYPES = ("IMAGE", "STRING")
20
+ RETURN_NAMES = ("IMAGE", "IMAGE_PATH")
21
+ OUTPUT_IS_LIST = (True, True)
22
+ FUNCTION = "load_image_batch"
23
+ CATEGORY = "🧪AILab/📝JoyCaption"
24
+
25
+ @classmethod
26
+ def IS_CHANGED(cls, **kwargs):
27
+ if 'sort_method' in kwargs and kwargs['sort_method'] == "random":
28
+ return float("NaN")
29
+ return hash(frozenset(kwargs))
30
+
31
+ def load_image_batch(self, image_dir: str, batch_size: int = 0, start_from: int = 1, sort_method: str = "sequential"):
32
+ if not os.path.isdir(image_dir):
33
+ raise FileNotFoundError(f"Directory '{image_dir}' cannot be found.")
34
+
35
+ valid_extensions = ['.jpg', '.jpeg', '.png', '.webp']
36
+ image_files = [f for f in os.listdir(image_dir) if any(f.lower().endswith(ext) for ext in valid_extensions)]
37
+
38
+ if not image_files:
39
+ raise FileNotFoundError(f"No valid images found in '{image_dir}'.")
40
+
41
+ if sort_method == "sequential":
42
+ image_files.sort()
43
+ elif sort_method == "reverse":
44
+ image_files.sort(reverse=True)
45
+ elif sort_method == "random":
46
+ import random
47
+ random.shuffle(image_files)
48
+
49
+ start_index = min(start_from - 1, len(image_files) - 1)
50
+ image_files = image_files[start_index:]
51
+ if batch_size > 0:
52
+ image_files = image_files[:batch_size]
53
+
54
+ images = []
55
+ image_paths = []
56
+ for filename in image_files:
57
+ img_path = os.path.join(image_dir, filename)
58
+ try:
59
+ image = ImageOps.exif_transpose(Image.open(img_path)).convert("RGB")
60
+ image = torch.from_numpy(np.array(image).astype(np.float32) / 255.0)[None,]
61
+ images.append(image)
62
+ image_paths.append(img_path)
63
+ except Exception as e:
64
+ print(f'\033[91mError loading {filename}: {str(e)}\033[0m')
65
+ continue
66
+
67
+ return (images, image_paths)
68
+
69
+ class CaptionSaver:
70
+ @classmethod
71
+ def INPUT_TYPES(cls):
72
+ return {
73
+ "required": {
74
+ "string": ("STRING", {"forceInput": True}),
75
+ "image_path": ("STRING", {"forceInput": True}),
76
+ },
77
+ "optional": {
78
+ "image": ("IMAGE",),
79
+ "custom_output_path": ("STRING", {"default": "", "multiline": True, "placeholder": "Custom output directory path. If empty, will use the directory of image_path"}),
80
+ "custom_file_name": ("STRING", {"default": "", "multiline": False, "placeholder": "Custom filename (without extension)"}),
81
+ "overwrite": ("BOOLEAN", {"default": True, "tooltip": "if true, will overwrite the existing txt file, if false, will add a number to the filename to make it unique"})
82
+ }
83
+ }
84
+
85
+ RETURN_TYPES = ()
86
+ FUNCTION = "save_caption"
87
+ CATEGORY = "🧪AILab/📝JoyCaption"
88
+ OUTPUT_NODE = True
89
+
90
+ def get_unique_filename(self, base_path: Path) -> Path:
91
+ """Get a unique filename by adding numbers if file exists."""
92
+ if not base_path.exists():
93
+ return base_path
94
+
95
+ counter = 1
96
+ while True:
97
+ new_path = base_path.parent / f"{base_path.stem}_{counter:02d}{base_path.suffix}"
98
+ if not new_path.exists():
99
+ return new_path
100
+ counter += 1
101
+
102
+ def save_caption(self, string, image_path, image=None, custom_output_path="", custom_file_name="", overwrite=True):
103
+ try:
104
+ image_path = Path(image_path)
105
+ save_dir = Path(custom_output_path.strip()) if custom_output_path.strip() else image_path.parent
106
+ save_dir.mkdir(parents=True, exist_ok=True)
107
+
108
+ try:
109
+ base_name = custom_file_name.strip() if custom_file_name.strip() else image_path.stem
110
+ txt_path = save_dir / f"{base_name}.txt"
111
+
112
+ if not overwrite and txt_path.exists():
113
+ txt_path = self.get_unique_filename(txt_path)
114
+ base_name = txt_path.stem
115
+
116
+ with open(txt_path, 'w', encoding='utf-8') as f:
117
+ f.write(string)
118
+ print(f'\033[93m[{txt_path.name}]:\033[0m {string}')
119
+
120
+ if image is not None and custom_output_path.strip():
121
+ try:
122
+ if isinstance(image, torch.Tensor):
123
+ while len(image.shape) > 3:
124
+ image = image.squeeze(0)
125
+
126
+ image = (image.cpu().numpy() * 255).astype(np.uint8)
127
+ if image.shape[-1] != 3:
128
+ image = np.transpose(image, (1, 2, 0))
129
+ image = Image.fromarray(image)
130
+
131
+ img_out_path = save_dir / f"{base_name}{image_path.suffix}"
132
+ image.save(img_out_path)
133
+
134
+ except Exception as e:
135
+ print(f'\033[91mFailed to copy image: {str(e)}\033[0m')
136
+
137
+ except Exception as e:
138
+ print(f'\033[91mError saving caption: {str(e)}\033[0m')
139
+
140
+ except Exception as e:
141
+ print(f'\033[91mCritical error: {str(e)}\033[0m')
142
+
143
+ return ()
144
+
145
+ NODE_CLASS_MAPPINGS = {
146
+ "ImageBatchPath": ImageBatchPath,
147
+ "CaptionSaver": CaptionSaver
148
+ }
149
+
150
+ NODE_DISPLAY_NAME_MAPPINGS = {
151
+ "ImageBatchPath": "Image Batch Path 🖼️",
152
+ "CaptionSaver": "Caption Saver 📝"
153
+ }
ComfyUI-JoyCaption/JC.py ADDED
@@ -0,0 +1,443 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers import AutoProcessor, LlavaForConditionalGeneration, BitsAndBytesConfig
3
+ import folder_paths
4
+ from pathlib import Path
5
+ from PIL import Image
6
+ from torchvision.transforms import ToPILImage
7
+ import json
8
+ import gc
9
+ import os
10
+
11
+ class ModelLoadError(Exception):
12
+ pass
13
+
14
+ def handle_model_error(e, cleanup_func=None):
15
+ if cleanup_func:
16
+ cleanup_func()
17
+ if torch.cuda.is_available():
18
+ torch.cuda.empty_cache()
19
+ gc.collect()
20
+ raise ModelLoadError(f"Error loading model: {str(e)}")
21
+
22
+ def cleanup_model_resources(model=None, processor=None):
23
+ if model is not None:
24
+ del model
25
+ if processor is not None:
26
+ del processor
27
+ if torch.cuda.is_available():
28
+ torch.cuda.empty_cache()
29
+ gc.collect()
30
+
31
+ def validate_model_parameters(quantization, valid_modes):
32
+ if quantization not in valid_modes:
33
+ raise ValueError(f"Invalid quantization mode: {quantization}. Valid modes: {', '.join(valid_modes)}")
34
+
35
+ with open(Path(__file__).parent / "jc_data.json", "r", encoding="utf-8") as f:
36
+ config = json.load(f)
37
+ CAPTION_TYPE_MAP = config["caption_type_map"]
38
+ EXTRA_OPTIONS = config["extra_options"]
39
+ MEMORY_EFFICIENT_CONFIGS = config["memory_efficient_configs"]
40
+ MODEL_SETTINGS = config["model_settings"]
41
+ CAPTION_LENGTH_CHOICES = config["caption_length_choices"]
42
+ HF_MODELS = config["hf_models"]
43
+
44
+ # --- Custom Models Merge Logic (for HF models only) ---
45
+ custom_path = Path(__file__).parent / "custom_models.json"
46
+
47
+ if custom_path.exists():
48
+ try:
49
+ with open(custom_path, "r", encoding="utf-8") as f:
50
+ custom_data = json.load(f) or {}
51
+ HF_MODELS.update(custom_data.get("hf_models", {}))
52
+ print("[JoyCaption] ✅ Loaded custom HF custom models.")
53
+ except Exception as e:
54
+ print(f"[JoyCaption] ⚠️ Failed to load custom models → {e}")
55
+ else:
56
+ print("[JoyCaption] ℹ️ No custom models found, skipping user-defined HF models.")
57
+ # ------------------------------------------------------
58
+
59
+ def build_prompt(caption_type: str, caption_length: str | int, extra_options: list[str], name_input: str) -> str:
60
+ """Constructs the prompt for the model based on user selections."""
61
+ if caption_length == "any":
62
+ map_idx = 0
63
+ elif isinstance(caption_length, str) and caption_length.isdigit():
64
+ map_idx = 1
65
+ else:
66
+ map_idx = 2
67
+
68
+ prompt = CAPTION_TYPE_MAP[caption_type][map_idx]
69
+
70
+ if extra_options:
71
+ prompt += " " + " ".join(extra_options)
72
+
73
+ return prompt.format(
74
+ name=name_input or "{NAME}",
75
+ length=caption_length,
76
+ word_count=caption_length,
77
+ )
78
+
79
+ _MODEL_CACHE = {}
80
+
81
+ class JC_Models:
82
+ """Handles loading, caching, and running the LLaVA models."""
83
+ def __init__(self, model: str, memory_mode: str):
84
+ cache_key = f"{model}_{memory_mode}"
85
+
86
+ if cache_key in _MODEL_CACHE:
87
+ try:
88
+ self.processor = _MODEL_CACHE[cache_key]["processor"]
89
+ self.model = _MODEL_CACHE[cache_key]["model"]
90
+ self.device = _MODEL_CACHE[cache_key]["device"]
91
+ if not next(self.model.parameters()).is_cuda:
92
+ raise RuntimeError("Cached model not on GPU")
93
+ print(f"Using cached model: {cache_key}")
94
+ return
95
+ except Exception as e:
96
+ print(f"Cache validation failed: {e}, reloading model...")
97
+ if cache_key in _MODEL_CACHE:
98
+ del _MODEL_CACHE[cache_key]
99
+ torch.cuda.empty_cache()
100
+
101
+ checkpoint_path = Path(folder_paths.models_dir) / "LLM" / Path(model).stem
102
+ if not checkpoint_path.exists():
103
+ from huggingface_hub import snapshot_download
104
+ snapshot_download(repo_id=model, local_dir=str(checkpoint_path), force_download=False, local_files_only=False)
105
+
106
+ self.device = "cuda" if torch.cuda.is_available() else "cpu"
107
+
108
+ if self.device == "cuda":
109
+ torch.backends.cudnn.benchmark = True
110
+ if hasattr(torch.backends, 'cuda'):
111
+ if hasattr(torch.backends.cuda, 'matmul'):
112
+ torch.backends.cuda.matmul.allow_tf32 = True
113
+ if hasattr(torch.backends.cuda, 'allow_tf32'):
114
+ torch.backends.cuda.allow_tf32 = True
115
+
116
+ os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "max_split_size_mb:128"
117
+
118
+ self.processor = AutoProcessor.from_pretrained(
119
+ str(checkpoint_path),
120
+ use_fast=True,
121
+ image_processor_type="CLIPImageProcessor",
122
+ image_size=336
123
+ )
124
+
125
+ if hasattr(self.processor, 'image_processor') and hasattr(self.processor.image_processor, 'size'):
126
+ expected_size = self.processor.image_processor.size
127
+ if isinstance(expected_size, dict):
128
+ self.target_size = (expected_size.get('height', 336), expected_size.get('width', 336))
129
+ elif isinstance(expected_size, (list, tuple)):
130
+ self.target_size = tuple(expected_size) if len(expected_size) == 2 else (expected_size[0], expected_size[0])
131
+ else:
132
+ self.target_size = (expected_size, expected_size)
133
+ else:
134
+ self.target_size = (336, 336)
135
+
136
+ model_kwargs = {
137
+ "device_map": "cuda" if self.device == "cuda" else "cpu",
138
+ }
139
+
140
+ try:
141
+ if "FP8-Dynamic" in model:
142
+ print("Loading FP8 model with automatic configuration...")
143
+ self.model = LlavaForConditionalGeneration.from_pretrained(
144
+ str(checkpoint_path),
145
+ torch_dtype="auto",
146
+ **model_kwargs
147
+ )
148
+ elif memory_mode == "Full Precision (bf16)":
149
+ self.model = LlavaForConditionalGeneration.from_pretrained(
150
+ str(checkpoint_path),
151
+ torch_dtype=torch.bfloat16,
152
+ **model_kwargs
153
+ )
154
+ elif memory_mode == "Balanced (8-bit)":
155
+ qnt_config = BitsAndBytesConfig(
156
+ load_in_8bit=True,
157
+ bnb_8bit_compute_dtype=torch.float16,
158
+ bnb_8bit_use_double_quant=True,
159
+ llm_int8_skip_modules=["vision_tower", "multi_modal_projector"],
160
+ llm_int8_enable_fp32_cpu_offload=True
161
+ )
162
+ self.model = LlavaForConditionalGeneration.from_pretrained(
163
+ str(checkpoint_path),
164
+ torch_dtype=torch.float16,
165
+ quantization_config=qnt_config,
166
+ **model_kwargs
167
+ )
168
+ else:
169
+ qnt_config = BitsAndBytesConfig(
170
+ load_in_4bit=True,
171
+ bnb_4bit_compute_dtype=torch.float16,
172
+ bnb_4bit_quant_type="nf4",
173
+ bnb_4bit_use_double_quant=True,
174
+ llm_int8_skip_modules=["vision_tower", "multi_modal_projector"],
175
+ llm_int8_enable_fp32_cpu_offload=True
176
+ )
177
+ self.model = LlavaForConditionalGeneration.from_pretrained(
178
+ str(checkpoint_path),
179
+ torch_dtype="auto",
180
+ quantization_config=qnt_config,
181
+ **model_kwargs
182
+ )
183
+
184
+ self.model.eval()
185
+
186
+ if self.device == "cuda" and not next(self.model.parameters()).is_cuda:
187
+ raise RuntimeError("Model failed to load on GPU")
188
+
189
+ if memory_mode == "Global Cache":
190
+ _MODEL_CACHE[cache_key] = {
191
+ "processor": self.processor,
192
+ "model": self.model,
193
+ "device": self.device
194
+ }
195
+
196
+ except Exception as e:
197
+ cleanup_model_resources(self.model, self.processor)
198
+ handle_model_error(e)
199
+
200
+ @torch.inference_mode()
201
+ def generate(self, image: Image.Image, system: str, prompt: str, max_new_tokens: int, temperature: float, top_p: float, top_k: int) -> str:
202
+ """Generates a caption for the given image."""
203
+ convo = [
204
+ {"role": "system", "content": system.strip()},
205
+ {"role": "user", "content": prompt.strip()},
206
+ ]
207
+
208
+ convo_string = self.processor.apply_chat_template(convo, tokenize=False, add_generation_prompt=True)
209
+ assert isinstance(convo_string, str)
210
+
211
+ if image.mode != 'RGB':
212
+ image = image.convert('RGB')
213
+
214
+ image = image.resize(self.target_size, Image.Resampling.LANCZOS)
215
+
216
+ inputs = self.processor(text=[convo_string], images=[image], return_tensors="pt").to(self.device)
217
+
218
+ if hasattr(inputs, 'pixel_values') and inputs['pixel_values'] is not None:
219
+ inputs['pixel_values'] = inputs['pixel_values'].to(self.model.dtype)
220
+
221
+ with torch.cuda.amp.autocast(enabled=True):
222
+ generate_ids = self.model.generate(
223
+ **inputs,
224
+ max_new_tokens=max_new_tokens,
225
+ do_sample=True if temperature > 0 else False,
226
+ suppress_tokens=None,
227
+ use_cache=True,
228
+ temperature=temperature,
229
+ top_k=None if top_k == 0 else top_k,
230
+ top_p=top_p,
231
+ )[0]
232
+
233
+ generate_ids = generate_ids[inputs['input_ids'].shape[1]:]
234
+ caption = self.processor.tokenizer.decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)
235
+ return caption.strip()
236
+
237
+ class JC_ExtraOptions:
238
+ """A node to collect extra options for captioning."""
239
+ @classmethod
240
+ def INPUT_TYPES(cls):
241
+ inputs = {"required": {}}
242
+ for key, value in EXTRA_OPTIONS.items():
243
+ inputs["required"][key] = ("BOOLEAN", {"default": value["default"]})
244
+ inputs["required"]["character_name"] = ("STRING", {"default": "", "multiline": True, "placeholder": "Character Name"})
245
+ return inputs
246
+
247
+ RETURN_TYPES = ("JOYCAPTION_EXTRA_OPTIONS",)
248
+ RETURN_NAMES = ("extra_options",)
249
+ FUNCTION = "get_extra_options"
250
+ CATEGORY = "🧪AILab/📝JoyCaption"
251
+
252
+ def get_extra_options(self, character_name, **kwargs):
253
+ ret_list = []
254
+ for key, value in EXTRA_OPTIONS.items():
255
+ if kwargs.get(key, False):
256
+ ret_list.append(value["description"])
257
+ return ([ret_list, character_name],)
258
+
259
+ class JC:
260
+ """The main, simple JoyCaption node."""
261
+ @classmethod
262
+ def INPUT_TYPES(cls):
263
+ model_list = list(HF_MODELS.keys())
264
+ return {
265
+ "required": {
266
+ "image": ("IMAGE",),
267
+ "model": (model_list, {"default": model_list[1], "tooltip": "Select the AI model to use for caption generation"}),
268
+ "quantization": (list(MEMORY_EFFICIENT_CONFIGS.keys()), {"default": "Balanced (8-bit)", "tooltip": "Choose between speed and quality. 8-bit is recommended for most users"}),
269
+ "prompt_style": (list(CAPTION_TYPE_MAP.keys()), {"default": "Descriptive", "tooltip": "Select the style of caption you want to generate"}),
270
+ "caption_length": (CAPTION_LENGTH_CHOICES, {"default": "any", "tooltip": "Control the length of the generated caption"}),
271
+ "memory_management": (["Keep in Memory", "Clear After Run", "Global Cache"], {"default": "Keep in Memory", "tooltip": "Choose how to manage model memory. 'Keep in Memory' for faster processing, 'Clear After Run' for limited VRAM, 'Global Cache' for fastest processing if you have enough VRAM"}),
272
+ },
273
+ "optional": {
274
+ "extra_options": ("JOYCAPTION_EXTRA_OPTIONS", {"tooltip": "Additional options to customize the caption generation"}),
275
+ }
276
+ }
277
+
278
+ RETURN_TYPES = ("STRING",)
279
+ RETURN_NAMES = ("STRING",)
280
+ FUNCTION = "generate"
281
+ CATEGORY = "🧪AILab/📝JoyCaption"
282
+
283
+ def __init__(self):
284
+ self.predictor = None
285
+ self.current_memory_mode = None
286
+ self.current_model = None
287
+
288
+ def generate(self, image, model, quantization, prompt_style, caption_length, memory_management, extra_options=None):
289
+ try:
290
+ validate_model_parameters(quantization, list(MEMORY_EFFICIENT_CONFIGS.keys()))
291
+
292
+ if memory_management == "Global Cache":
293
+ try:
294
+ model_name = HF_MODELS[model]["name"]
295
+ self.predictor = JC_Models(model_name, quantization)
296
+ except Exception as e:
297
+ return (f"Error loading model: {e}",)
298
+ elif self.predictor is None or self.current_memory_mode != quantization or self.current_model != model:
299
+ if self.predictor is not None:
300
+ del self.predictor
301
+ self.predictor = None
302
+ torch.cuda.empty_cache()
303
+ gc.collect()
304
+ try:
305
+ model_name = HF_MODELS[model]["name"]
306
+ self.predictor = JC_Models(model_name, quantization)
307
+ self.current_memory_mode = quantization
308
+ self.current_model = model
309
+ except Exception as e:
310
+ return (f"Error loading model: {e}",)
311
+
312
+ prompt = build_prompt(prompt_style, caption_length, extra_options[0] if extra_options else [], extra_options[1] if extra_options else "{NAME}")
313
+ system_prompt = MODEL_SETTINGS["default_system_prompt"]
314
+ pil_image = ToPILImage()(image[0].permute(2, 0, 1))
315
+
316
+ response = self.predictor.generate(
317
+ image=pil_image,
318
+ system=system_prompt,
319
+ prompt=prompt,
320
+ max_new_tokens=MODEL_SETTINGS["default_max_tokens"],
321
+ temperature=MODEL_SETTINGS["default_temperature"],
322
+ top_p=MODEL_SETTINGS["default_top_p"],
323
+ top_k=MODEL_SETTINGS["default_top_k"],
324
+ )
325
+
326
+ if memory_management == "Clear After Run":
327
+ del self.predictor
328
+ self.predictor = None
329
+ torch.cuda.empty_cache()
330
+ gc.collect()
331
+
332
+ return (response,)
333
+ except Exception as e:
334
+ if memory_management == "Clear After Run":
335
+ del self.predictor
336
+ self.predictor = None
337
+ torch.cuda.empty_cache()
338
+ gc.collect()
339
+ raise e
340
+
341
+ class JC_adv:
342
+ """The advanced JoyCaption node with more settings."""
343
+ @classmethod
344
+ def INPUT_TYPES(cls):
345
+ model_list = list(HF_MODELS.keys())
346
+ return {
347
+ "required": {
348
+ "image": ("IMAGE",),
349
+ "model": (model_list, {"default": model_list[1], "tooltip": "Select the AI model to use for caption generation"}),
350
+ "quantization": (list(MEMORY_EFFICIENT_CONFIGS.keys()), {"default": "Balanced (8-bit)", "tooltip": "Choose between speed and quality. 8-bit is recommended for most users"}),
351
+ "prompt_style": (list(CAPTION_TYPE_MAP.keys()), {"default": "Descriptive", "tooltip": "Select the style of caption you want to generate"}),
352
+ "caption_length": (CAPTION_LENGTH_CHOICES, {"default": "any", "tooltip": "Control the length of the generated caption"}),
353
+ "max_new_tokens": ("INT", {"default": MODEL_SETTINGS["default_max_tokens"], "min": 1, "max": 2048, "tooltip": "Maximum number of tokens to generate. Higher values allow longer captions"}),
354
+ "temperature": ("FLOAT", {"default": MODEL_SETTINGS["default_temperature"], "min": 0.0, "max": 2.0, "step": 0.05, "tooltip": "Control the randomness of the output. Higher values make the output more creative but less predictable"}),
355
+ "top_p": ("FLOAT", {"default": MODEL_SETTINGS["default_top_p"], "min": 0.0, "max": 1.0, "step": 0.01, "tooltip": "Control the diversity of the output. Higher values allow more diverse word choices"}),
356
+ "top_k": ("INT", {"default": MODEL_SETTINGS["default_top_k"], "min": 0, "max": 100, "tooltip": "Limit the number of possible next tokens. Lower values make the output more focused"}),
357
+ "custom_prompt": ("STRING", {"default": "", "multiline": True, "tooltip": "Custom prompt template. If empty, will use the selected prompt style"}),
358
+ "memory_management": (["Keep in Memory", "Clear After Run", "Global Cache"], {"default": "Keep in Memory", "tooltip": "Choose how to manage model memory. 'Keep in Memory' for faster processing, 'Clear After Run' for limited VRAM, 'Global Cache' for fastest processing if you have enough VRAM"}),
359
+ },
360
+ "optional": {
361
+ "extra_options": ("JOYCAPTION_EXTRA_OPTIONS", {"tooltip": "Additional options to customize the caption generation"}),
362
+ }
363
+ }
364
+
365
+ RETURN_TYPES = ("STRING", "STRING")
366
+ RETURN_NAMES = ("PROMPT", "STRING")
367
+ FUNCTION = "generate"
368
+ CATEGORY = "🧪AILab/📝JoyCaption"
369
+
370
+ def __init__(self):
371
+ self.predictor = None
372
+ self.current_memory_mode = None
373
+ self.current_model = None
374
+
375
+ def generate(self, image, model, quantization, prompt_style, caption_length, max_new_tokens, temperature, top_p, top_k, custom_prompt, memory_management, extra_options=None):
376
+ try:
377
+ validate_model_parameters(quantization, list(MEMORY_EFFICIENT_CONFIGS.keys()))
378
+
379
+ if memory_management == "Global Cache":
380
+ try:
381
+ model_name = HF_MODELS[model]["name"]
382
+ self.predictor = JC_Models(model_name, quantization)
383
+ except Exception as e:
384
+ return (f"Error loading model: {e}", "")
385
+ elif self.predictor is None or self.current_memory_mode != quantization or self.current_model != model:
386
+ if self.predictor is not None:
387
+ del self.predictor
388
+ self.predictor = None
389
+ torch.cuda.empty_cache()
390
+ gc.collect()
391
+ try:
392
+ model_name = HF_MODELS[model]["name"]
393
+ self.predictor = JC_Models(model_name, quantization)
394
+ self.current_memory_mode = quantization
395
+ self.current_model = model
396
+ except Exception as e:
397
+ return (f"Error loading model: {e}", "")
398
+
399
+ if custom_prompt and custom_prompt.strip():
400
+ prompt = custom_prompt.strip()
401
+ else:
402
+ prompt = build_prompt(prompt_style, caption_length, extra_options[0] if extra_options else [], extra_options[1] if extra_options else "{NAME}")
403
+
404
+ system_prompt = MODEL_SETTINGS["default_system_prompt"]
405
+ pil_image = ToPILImage()(image[0].permute(2, 0, 1))
406
+
407
+ response = self.predictor.generate(
408
+ image=pil_image,
409
+ system=system_prompt,
410
+ prompt=prompt,
411
+ max_new_tokens=max_new_tokens,
412
+ temperature=temperature,
413
+ top_p=top_p,
414
+ top_k=top_k,
415
+ )
416
+
417
+ if memory_management == "Clear After Run":
418
+ del self.predictor
419
+ self.predictor = None
420
+ torch.cuda.empty_cache()
421
+ gc.collect()
422
+
423
+ return (prompt, response)
424
+ except Exception as e:
425
+ if memory_management == "Clear After Run":
426
+ del self.predictor
427
+ self.predictor = None
428
+ torch.cuda.empty_cache()
429
+ gc.collect()
430
+ raise e
431
+
432
+ NODE_CLASS_MAPPINGS = {
433
+ "JC": JC,
434
+ "JC_adv": JC_adv,
435
+ "JC_ExtraOptions": JC_ExtraOptions,
436
+ }
437
+
438
+ NODE_DISPLAY_NAME_MAPPINGS = {
439
+ "JC": "JoyCaption",
440
+ "JC_adv": "JoyCaption (Advanced)",
441
+ "JC_ExtraOptions": "JoyCaption Extra Options",
442
+ }
443
+
ComfyUI-JoyCaption/JC_GGUF.py ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import folder_paths
3
+ from pathlib import Path
4
+ from PIL import Image
5
+ from torchvision.transforms import ToPILImage
6
+ import json
7
+ from llama_cpp import Llama
8
+ from llama_cpp.llama_chat_format import Llava15ChatHandler
9
+ import base64
10
+ import io
11
+ import sys
12
+ import gc
13
+ import os
14
+ from huggingface_hub import hf_hub_download
15
+
16
+ class ModelLoadError(Exception):
17
+ pass
18
+
19
+ def suppress_output(func):
20
+ import sys
21
+ import io
22
+ def wrapper(*args, **kwargs):
23
+ old_stdout = sys.stdout
24
+ old_stderr = sys.stderr
25
+ try:
26
+ sys.stdout = io.StringIO()
27
+ sys.stderr = io.StringIO()
28
+ return func(*args, **kwargs)
29
+ finally:
30
+ sys.stdout = old_stdout
31
+ sys.stderr = old_stderr
32
+ return wrapper
33
+
34
+ os.environ['TRANSFORMERS_VERBOSITY'] = 'error'
35
+ os.environ['TOKENIZERS_PARALLELISM'] = 'false'
36
+
37
+ if torch.cuda.is_available():
38
+ torch.backends.cudnn.benchmark = True
39
+ if hasattr(torch.backends, 'cuda'):
40
+ if hasattr(torch.backends.cuda, 'matmul'):
41
+ torch.backends.cuda.matmul.allow_tf32 = True
42
+ if hasattr(torch.backends.cuda, 'allow_tf32'):
43
+ torch.backends.cuda.allow_tf32 = True
44
+ os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "max_split_size_mb:128"
45
+
46
+ with open(Path(__file__).parent / "jc_data.json", "r", encoding="utf-8") as f:
47
+ config = json.load(f)
48
+ CAPTION_TYPE_MAP = config["caption_type_map"]
49
+ EXTRA_OPTIONS = config["extra_options"]
50
+ MODEL_SETTINGS = config["model_settings"]
51
+ CAPTION_LENGTH_CHOICES = config["caption_length_choices"]
52
+ GGUF_MODELS = config["gguf_models"]
53
+ GGUF_SETTINGS = config["gguf_settings"]
54
+
55
+ # --- Custom Models Merge Logic (for GGUF models only) ---
56
+ custom_path = Path(__file__).parent / "custom_models.json"
57
+
58
+ if custom_path.exists():
59
+ try:
60
+ with open(custom_path, "r", encoding="utf-8") as f:
61
+ custom_data = json.load(f) or {}
62
+ GGUF_MODELS.update(custom_data.get("gguf_models", {}))
63
+ print("[JoyCaption GGUF] ✅ Loaded custom GGUF custom models")
64
+ except Exception as e:
65
+ print(f"[JoyCaption GGUF] ⚠️ Failed to load custom models → {e}")
66
+ else:
67
+ print("[JoyCaption GGUF] ℹ️ No custom models found, skipping user-defined GGUF models.")
68
+ # -------------------------------------------------------
69
+
70
+ _MODEL_CACHE = {}
71
+
72
+ def build_prompt(caption_type: str, caption_length: str | int, extra_options: list[str], name_input: str) -> str:
73
+ if caption_length == "any":
74
+ map_idx = 0
75
+ elif isinstance(caption_length, str) and caption_length.isdigit():
76
+ map_idx = 1
77
+ else:
78
+ map_idx = 2
79
+
80
+ prompt = CAPTION_TYPE_MAP[caption_type][map_idx]
81
+ if extra_options:
82
+ prompt += " " + " ".join(extra_options)
83
+ return prompt.format(name=name_input or "{NAME}", length=caption_length, word_count=caption_length)
84
+
85
+ class JC_GGUF_Models:
86
+ def __init__(self, model: str, processing_mode: str):
87
+ try:
88
+ models_dir = Path(folder_paths.models_dir).resolve()
89
+ llm_models_dir = (models_dir / "LLM" / "GGUF").resolve()
90
+ llm_models_dir.mkdir(parents=True, exist_ok=True)
91
+
92
+ model_filename = Path(model).name
93
+ local_path = llm_models_dir / model_filename
94
+
95
+ if not local_path.exists():
96
+ if "/" not in model:
97
+ raise ValueError("Invalid model path")
98
+ repo_path, filename = model.rsplit("/", 1)
99
+ local_path = Path(hf_hub_download(
100
+ repo_id=repo_path,
101
+ filename=filename,
102
+ local_dir=str(llm_models_dir),
103
+ local_dir_use_symlinks=False
104
+ )).resolve()
105
+
106
+ mmproj_filename = GGUF_SETTINGS["mmproj_filename"]
107
+ mmproj_path = llm_models_dir / mmproj_filename
108
+ if not mmproj_path.exists():
109
+ mmproj_path = Path(hf_hub_download(
110
+ repo_id="concedo/llama-joycaption-beta-one-hf-llava-mmproj-gguf",
111
+ filename=mmproj_filename,
112
+ local_dir=str(llm_models_dir),
113
+ local_dir_use_symlinks=False
114
+ )).resolve()
115
+
116
+ n_ctx = MODEL_SETTINGS["context_window"]
117
+ n_batch = 2048
118
+ n_threads = max(4, MODEL_SETTINGS["cpu_threads"])
119
+ if processing_mode == "Auto":
120
+ n_gpu_layers = -1 if torch.cuda.is_available() else 0
121
+ elif processing_mode == "GPU":
122
+ n_gpu_layers = -1
123
+ else: # CPU
124
+ n_gpu_layers = 0
125
+
126
+ self.model = self._initialize_model(local_path, mmproj_path, n_ctx, n_batch, n_threads, n_gpu_layers)
127
+
128
+ except Exception as e:
129
+ raise ModelLoadError(f"Model initialization failed: {str(e)}")
130
+
131
+ @suppress_output
132
+ def _initialize_model(self, local_path, mmproj_path, n_ctx, n_batch, n_threads, n_gpu_layers):
133
+ """Initialize the GGUF model with suppressed output"""
134
+ return Llama(
135
+ model_path=str(local_path),
136
+ n_ctx=n_ctx,
137
+ n_batch=n_batch,
138
+ n_threads=n_threads,
139
+ n_gpu_layers=n_gpu_layers,
140
+ verbose=False,
141
+ chat_handler=Llava15ChatHandler(clip_model_path=str(mmproj_path)),
142
+ offload_kqv=True,
143
+ numa=True
144
+ )
145
+
146
+ def generate(self, image: Image.Image, system: str, prompt: str, max_new_tokens: int, temperature: float, top_p: float, top_k: int) -> str:
147
+ try:
148
+ if image.mode != 'RGB':
149
+ image = image.convert('RGB')
150
+
151
+ image = image.resize(GGUF_SETTINGS["default_image_size"], Image.Resampling.BILINEAR)
152
+
153
+ import io
154
+ import base64
155
+
156
+ img_buffer = io.BytesIO()
157
+ image.save(img_buffer, format='PNG')
158
+ img_buffer.seek(0)
159
+
160
+ img_base64 = base64.b64encode(img_buffer.read()).decode('utf-8')
161
+ data_uri = f"data:image/png;base64,{img_base64}"
162
+
163
+ messages = [
164
+ {"role": "system", "content": system.strip()},
165
+ {
166
+ "role": "user",
167
+ "content": [
168
+ {"type": "text", "text": prompt.strip()},
169
+ {"type": "image_url", "image_url": {"url": data_uri}}
170
+ ]
171
+ }
172
+ ]
173
+
174
+ completion_params = {
175
+ "messages": messages,
176
+ "max_tokens": max_new_tokens,
177
+ "temperature": temperature,
178
+ "top_p": top_p,
179
+ "stop": ["</s>", "User:", "Assistant:"],
180
+ "stream": False,
181
+ "repeat_penalty": 1.1,
182
+ "mirostat_mode": 0
183
+ }
184
+
185
+ if top_k > 0:
186
+ completion_params["top_k"] = top_k
187
+
188
+ response = self._create_completion(completion_params)
189
+
190
+ del messages
191
+
192
+ return response["choices"][0]["message"]["content"].strip()
193
+
194
+ except Exception as e:
195
+ return f"Generation error: {str(e)}"
196
+ finally:
197
+ gc.collect()
198
+
199
+ @suppress_output
200
+ def _create_completion(self, completion_params):
201
+ """Create chat completion with suppressed output"""
202
+ return self.model.create_chat_completion(**completion_params)
203
+
204
+ class JC_GGUF:
205
+ @classmethod
206
+ def INPUT_TYPES(cls):
207
+ model_list = list(GGUF_MODELS.keys())
208
+ return {
209
+ "required": {
210
+ "image": ("IMAGE",),
211
+ "model": (model_list, {"default": model_list[0], "tooltip": "Select the GGUF model to use for caption generation"}),
212
+ "processing_mode": (["Auto", "GPU", "CPU"], {"default": "Auto", "tooltip": "Auto: Automatically detect best mode\nGPU: Faster but requires more VRAM\nCPU: Slower but saves VRAM"}),
213
+ "prompt_style": (list(CAPTION_TYPE_MAP.keys()), {"default": "Descriptive", "tooltip": "Select the style of caption you want to generate"}),
214
+ "caption_length": (CAPTION_LENGTH_CHOICES, {"default": "any", "tooltip": "Control the length of the generated caption"}),
215
+ "memory_management": (["Keep in Memory", "Clear After Run", "Global Cache"], {"default": "Keep in Memory", "tooltip": "Choose how to manage model memory. 'Keep in Memory' for faster processing, 'Clear After Run' for limited VRAM, 'Global Cache' for fastest processing if you have enough VRAM"}),
216
+ },
217
+ "optional": {
218
+ "extra_options": ("JOYCAPTION_EXTRA_OPTIONS", {"tooltip": "Additional options to customize the caption generation"}),
219
+ }
220
+ }
221
+
222
+ RETURN_TYPES = ("STRING",)
223
+ RETURN_NAMES = ("STRING",)
224
+ FUNCTION = "generate"
225
+ CATEGORY = "🧪AILab/📝JoyCaption"
226
+
227
+ def __init__(self):
228
+ self.predictor = None
229
+ self.current_processing_mode = None
230
+ self.current_model = None
231
+
232
+ def generate(self, image, model, processing_mode, prompt_style, caption_length, memory_management, extra_options=None):
233
+ try:
234
+ print(f"JoyCaption GGUF: Processing image with {model} ({processing_mode} mode)")
235
+ cache_key = f"{model}_{processing_mode}"
236
+
237
+ if memory_management == "Global Cache":
238
+ try:
239
+ if cache_key in _MODEL_CACHE:
240
+ self.predictor = _MODEL_CACHE[cache_key]
241
+ else:
242
+ model_name = GGUF_MODELS[model]["name"]
243
+ self.predictor = JC_GGUF_Models(model_name, processing_mode)
244
+ _MODEL_CACHE[cache_key] = self.predictor
245
+ except Exception as e:
246
+ return (f"Error loading model: {e}",)
247
+ elif self.predictor is None or self.current_processing_mode != processing_mode or self.current_model != model:
248
+ if self.predictor is not None:
249
+ del self.predictor
250
+ self.predictor = None
251
+ torch.cuda.empty_cache()
252
+ try:
253
+ model_name = GGUF_MODELS[model]["name"]
254
+ self.predictor = JC_GGUF_Models(model_name, processing_mode)
255
+ self.current_processing_mode = processing_mode
256
+ self.current_model = model
257
+ except Exception as e:
258
+ return (f"Error loading model: {e}",)
259
+
260
+ prompt_text = build_prompt(prompt_style, caption_length, extra_options[0] if extra_options else [], extra_options[1] if extra_options else "{NAME}")
261
+
262
+ print("JoyCaption GGUF: Generating caption...")
263
+ with torch.inference_mode():
264
+ pil_image = ToPILImage()(image[0].permute(2, 0, 1))
265
+ response = self.predictor.generate(
266
+ image=pil_image,
267
+ system=MODEL_SETTINGS["default_system_prompt"],
268
+ prompt=prompt_text,
269
+ max_new_tokens=MODEL_SETTINGS["default_max_tokens"],
270
+ temperature=MODEL_SETTINGS["default_temperature"],
271
+ top_p=MODEL_SETTINGS["default_top_p"],
272
+ top_k=MODEL_SETTINGS["default_top_k"],
273
+ )
274
+ print("JoyCaption GGUF: Caption generation completed")
275
+
276
+ if memory_management == "Clear After Run":
277
+ del self.predictor
278
+ self.predictor = None
279
+ torch.cuda.empty_cache()
280
+ gc.collect()
281
+
282
+ return (response,)
283
+ except Exception as e:
284
+ if memory_management == "Clear After Run":
285
+ del self.predictor
286
+ self.predictor = None
287
+ torch.cuda.empty_cache()
288
+ gc.collect()
289
+ raise e
290
+
291
+ class JC_GGUF_adv:
292
+ @classmethod
293
+ def INPUT_TYPES(cls):
294
+ model_list = list(GGUF_MODELS.keys())
295
+ return {
296
+ "required": {
297
+ "image": ("IMAGE",),
298
+ "model": (model_list, {"default": model_list[0], "tooltip": "Select the GGUF model to use for caption generation"}),
299
+ "processing_mode": (["Auto", "GPU", "CPU"], {"default": "Auto", "tooltip": "Auto: Automatically detect best mode\nGPU: Faster but requires more VRAM\nCPU: Slower but saves VRAM"}),
300
+ "prompt_style": (list(CAPTION_TYPE_MAP.keys()), {"default": "Descriptive", "tooltip": "Select the style of caption you want to generate"}),
301
+ "caption_length": (CAPTION_LENGTH_CHOICES, {"default": "any", "tooltip": "Control the length of the generated caption"}),
302
+ "max_new_tokens": ("INT", {"default": MODEL_SETTINGS["default_max_tokens"], "min": 1, "max": 2048, "tooltip": "Maximum number of tokens to generate. Higher values allow longer captions"}),
303
+ "temperature": ("FLOAT", {"default": MODEL_SETTINGS["default_temperature"], "min": 0.0, "max": 2.0, "step": 0.05, "tooltip": "Control the randomness of the output. Higher values make the output more creative but less predictable"}),
304
+ "top_p": ("FLOAT", {"default": MODEL_SETTINGS["default_top_p"], "min": 0.0, "max": 1.0, "step": 0.01, "tooltip": "Control the diversity of the output. Higher values allow more diverse word choices"}),
305
+ "top_k": ("INT", {"default": MODEL_SETTINGS["default_top_k"], "min": 0, "max": 100, "tooltip": "Limit the number of possible next tokens. Lower values make the output more focused"}),
306
+ "custom_prompt": ("STRING", {"default": "", "multiline": True, "tooltip": "Custom prompt template. If empty, will use the selected prompt style"}),
307
+ "memory_management": (["Keep in Memory", "Clear After Run", "Global Cache"], {"default": "Keep in Memory", "tooltip": "Choose how to manage model memory. 'Keep in Memory' for faster processing, 'Clear After Run' for limited VRAM, 'Global Cache' for fastest processing if you have enough VRAM"}),
308
+ },
309
+ "optional": {
310
+ "extra_options": ("JOYCAPTION_EXTRA_OPTIONS", {"tooltip": "Additional options to customize the caption generation"}),
311
+ }
312
+ }
313
+
314
+ RETURN_TYPES = ("STRING", "STRING")
315
+ RETURN_NAMES = ("PROMPT", "STRING")
316
+ FUNCTION = "generate"
317
+ CATEGORY = "🧪AILab/📝JoyCaption"
318
+
319
+ def __init__(self):
320
+ self.predictor = None
321
+ self.current_processing_mode = None
322
+ self.current_model = None
323
+
324
+ def generate(self, image, model, processing_mode, prompt_style, caption_length, max_new_tokens, temperature, top_p, top_k, custom_prompt, memory_management, extra_options=None):
325
+ try:
326
+ cache_key = f"{model}_{processing_mode}"
327
+
328
+ if memory_management == "Global Cache":
329
+ try:
330
+ if cache_key in _MODEL_CACHE:
331
+ self.predictor = _MODEL_CACHE[cache_key]
332
+ else:
333
+ model_name = GGUF_MODELS[model]["name"]
334
+ self.predictor = JC_GGUF_Models(model_name, processing_mode)
335
+ _MODEL_CACHE[cache_key] = self.predictor
336
+ except Exception as e:
337
+ return ("", f"Error loading model: {e}")
338
+ elif self.predictor is None or self.current_processing_mode != processing_mode or self.current_model != model:
339
+ if self.predictor is not None:
340
+ del self.predictor
341
+ self.predictor = None
342
+ torch.cuda.empty_cache()
343
+ try:
344
+ model_name = GGUF_MODELS[model]["name"]
345
+ self.predictor = JC_GGUF_Models(model_name, processing_mode)
346
+ self.current_processing_mode = processing_mode
347
+ self.current_model = model
348
+ except Exception as e:
349
+ return ("", f"Error loading model: {e}")
350
+
351
+ prompt = custom_prompt if custom_prompt.strip() else build_prompt(prompt_style, caption_length, extra_options[0] if extra_options else [], extra_options[1] if extra_options else "{NAME}")
352
+ system_prompt = MODEL_SETTINGS["default_system_prompt"]
353
+
354
+ pil_image = ToPILImage()(image[0].permute(2, 0, 1))
355
+ response = self.predictor.generate(
356
+ image=pil_image,
357
+ system=system_prompt,
358
+ prompt=prompt,
359
+ max_new_tokens=max_new_tokens,
360
+ temperature=temperature,
361
+ top_p=top_p,
362
+ top_k=top_k,
363
+ )
364
+
365
+ if memory_management == "Clear After Run":
366
+ del self.predictor
367
+ self.predictor = None
368
+ torch.cuda.empty_cache()
369
+ gc.collect()
370
+
371
+ return (prompt, response)
372
+ except Exception as e:
373
+ if memory_management == "Clear After Run":
374
+ del self.predictor
375
+ self.predictor = None
376
+ torch.cuda.empty_cache()
377
+ gc.collect()
378
+ return ("", f"Error: {str(e)}")
379
+
380
+ NODE_CLASS_MAPPINGS = {
381
+ "JC_GGUF": JC_GGUF,
382
+ "JC_GGUF_adv": JC_GGUF_adv,
383
+ }
384
+
385
+ NODE_DISPLAY_NAME_MAPPINGS = {
386
+ "JC_GGUF": "JoyCaption GGUF",
387
+ "JC_GGUF_adv": "JoyCaption GGUF (Advanced)",
388
+ }
ComfyUI-JoyCaption/LICENSE ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <https://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
ComfyUI-JoyCaption/README.md ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ComfyUI-JoyCaption
2
+
3
+ Joy Caption is a ComfyUI custom node powered by the LLaVA model for efficient, stylized image captioning. Caption Tools nodes handle batch image processing and automatic separation of caption text.
4
+
5
+ ![Joycaption_node](example_workflows/Joycaption_node.png)
6
+
7
+ ## News & Updates
8
+ - **2025/10/27**: Added Custom Models **v2.0.2** ( [update.md](https://github.com/1038lab/ComfyUI-JoyCaption/blob/main/update.md#v202-2025-10-27) )
9
+ - **2025/10/20**: Update and bug fix ComfyUI-JoyCaption to **v2.0.1** ( [update.md](https://github.com/1038lab/ComfyUI-JoyCaption/blob/main/update.md#v201-2025-10-20) )
10
+ - **2025/08/22**: Update ComfyUI-JoyCaption to **v2.0.0** ( [update.md](https://github.com/1038lab/ComfyUI-JoyCaption/blob/main/update.md#v200-2025-08-22) )
11
+ ![Joycaption GGUF](example_workflows/JoyCaption-GGUF.png)
12
+ - Added GGUF model support for better performance and compatibility
13
+ - Fixed critical parameter handling issues (top_k, image format)
14
+ - Improved console output (no more base64 spam)
15
+ - Enhanced error handling and stability
16
+ - Added JoyCaption GGUF and JoyCaption GGUF (Advanced) nodes
17
+ - **Enhanced GGUF Support**: Comprehensive support for 12 quantization levels (Q2_K to F16)
18
+ - **llama_cpp_install folder**: [Complete installation guides](https://github.com/1038lab/ComfyUI-JoyCaption/blob/main/llama_cpp_install/llama_cpp_install.md) and automated scripts for llama-cpp-python
19
+ - **Simplified Installation**: [One-click llama-cpp-python installation](https://github.com/1038lab/ComfyUI-JoyCaption/tree/main/llama_cpp_install) with automatic CUDA support
20
+ - **Cross-Platform Support**: Windows, macOS, and Linux installation guides
21
+ - **Performance Improvements**: Optimized model loading and memory management
22
+
23
+ - **2025/06/15**: Update ComfyUI-JoyCaption to **v1.2.0** ( [update.md](https://github.com/1038lab/ComfyUI-JoyCaption/blob/main/update.md#v120-20250615) )
24
+ - Enhanced CUDA performance optimization
25
+ - Improved memory management strategies
26
+ - Added Global Cache mode for faster processing
27
+
28
+ ![v1 2 0](https://github.com/user-attachments/assets/bcb6cadd-1294-4fd0-a5b4-fe8cd3784801)
29
+
30
+ - **2025/06/07**: Update ComfyUI-JoyCaption to **v1.1.1** ( [update.md](https://github.com/1038lab/ComfyUI-JoyCaption/blob/main/update.md#v111-20250607) )
31
+
32
+ - **2025/06/05**: Update ComfyUI-JoyCaption to **v1.1.0** ( [update.md](https://github.com/1038lab/ComfyUI-JoyCaption/blob/main/update.md#v110-20250605) )
33
+ - Add Caption tools
34
+
35
+ [![Joycaption_node](example_workflows/batch_image_text_output.jpg)](https://github.com/1038lab/ComfyUI-JoyCaption/blob/main/example_workflows/batch_image_text_output.json)
36
+
37
+ ## Features
38
+
39
+ - Simple and user-friendly interface
40
+ - Multiple caption types support
41
+ - Flexible length control
42
+ - Memory optimization options
43
+ - **GGUF model support** - Efficient quantized models for better performance and lower memory usage
44
+ - **Automatic model download** - Models will be downloaded automatically and properly renamed on first use
45
+ - Support for multiple caption types
46
+ - Support for advanced customization options
47
+ - Multiple precision options (fp32, bf16, fp16, 8-bit, 4-bit)
48
+ - Enhanced memory management with Global Cache mode
49
+ - Clean console output (no debug spam)
50
+ - Robust error handling and parameter validation
51
+ - **llama_cpp_install folder** - Complete installation guides and automated scripts for llama-cpp-python
52
+
53
+ ## Installation
54
+
55
+ 1. Clone this repository to your `ComfyUI/custom_nodes` directory:
56
+ ```bash
57
+ cd ComfyUI/custom_nodes
58
+ git clone https://github.com/1038lab/ComfyUI-JoyCaption.git
59
+ ```
60
+
61
+ 2. Install the required dependencies:
62
+ ```bash
63
+ cd ComfyUI/custom_nodes/ComfyUI-JoyCaption
64
+ pip install -r requirements.txt
65
+ ```
66
+
67
+ 3. **For GGUF Models (Recommended)**: Install llama-cpp-python with CUDA support:
68
+ ```bash
69
+ # Option 1: Automated installation (Recommended)
70
+ python llama_cpp_install/llama_cpp_install.py
71
+
72
+ # Option 2: Manual installation
73
+ pip install -r requirements_gguf.txt
74
+ ```
75
+
76
+ **Installation Guides Available:**
77
+ - **English**: [llama_cpp_install/llama_cpp_install.md](llama_cpp_install/llama_cpp_install.md)
78
+ - **中文**: [llama_cpp_install/llama_cpp_install_zh.md](llama_cpp_install/llama_cpp_install_zh.md)
79
+
80
+ ## Download Models
81
+ The models will be automatically downloaded and renamed on first use, or you can manually download them:
82
+
83
+ ### Standard Models (HuggingFace Format)
84
+ | Model | Link | Memory Usage |
85
+ | ----- | ---- | ------------ |
86
+ | JoyCaption Beta One | [Download](https://huggingface.co/fancyfeast/llama-joycaption-beta-one-hf-llava) | ~8-16GB |
87
+ | JoyCaption Alpha Two | [Download](https://huggingface.co/fancyfeast/llama-joycaption-alpha-two-hf-llava) | ~8-16GB |
88
+
89
+ ### GGUF Models (Quantized, Recommended)
90
+ | Model | Size | Memory Usage | Quality | Recommended For | Link |
91
+ | ----- | ---- | ------------ | ------- | --------------- | ---- |
92
+ | JoyCaption Beta One (Q2_K) | 3.18GB | ~4GB | Good | Low VRAM (6GB+) | [Download](https://huggingface.co/mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/resolve/main/llama-joycaption-beta-one-hf-llava.Q2_K.gguf) |
93
+ | JoyCaption Beta One (Q3_K_S) | 3.66GB | ~5GB | Good+ | Budget systems (8GB+) | [Download](https://huggingface.co/mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/resolve/main/llama-joycaption-beta-one-hf-llava.Q3_K_S.gguf) |
94
+ | JoyCaption Beta One (Q3_K_M) | 4.02GB | ~5GB | Better | Balanced performance | [Download](https://huggingface.co/mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/resolve/main/llama-joycaption-beta-one-hf-llava.Q3_K_M.gguf) |
95
+ | JoyCaption Beta One (Q3_K_L) | 4.32GB | ~6GB | Better+ | Good quality/size ratio | [Download](https://huggingface.co/mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/resolve/main/llama-joycaption-beta-one-hf-llava.Q3_K_L.gguf) |
96
+ | JoyCaption Beta One (IQ4_XS) | 4.48GB | ~6GB | Very Good | **Recommended** (8GB+) | [Download](https://huggingface.co/mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/resolve/main/llama-joycaption-beta-one-hf-llava.IQ4_XS.gguf) |
97
+ | JoyCaption Beta One (Q4_K_S) | 4.69GB | ~6GB | Very Good | Quality focused | [Download](https://huggingface.co/mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/resolve/main/llama-joycaption-beta-one-hf-llava.Q4_K_S.gguf) |
98
+ | JoyCaption Beta One (Q4_K_M) | 4.92GB | ~7GB | Very Good+ | Balanced choice | [Download](https://huggingface.co/mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/resolve/main/llama-joycaption-beta-one-hf-llava.Q4_K_M.gguf) |
99
+ | JoyCaption Beta One (Q5_K_S) | 5.60GB | ~7GB | Excellent | High quality (10GB+) | [Download](https://huggingface.co/mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/resolve/main/llama-joycaption-beta-one-hf-llava.Q5_K_S.gguf) |
100
+ | JoyCaption Beta One (Q5_K_M) | 5.73GB | ~8GB | Excellent+ | Premium quality | [Download](https://huggingface.co/mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/resolve/main/llama-joycaption-beta-one-hf-llava.Q5_K_M.gguf) |
101
+ | JoyCaption Beta One (Q6_K) | 6.60GB | ~8GB | Near Original | Maximum quality (12GB+) | [Download](https://huggingface.co/mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/resolve/main/llama-joycaption-beta-one-hf-llava.Q6_K.gguf) |
102
+ | JoyCaption Beta One (Q8_0) | 8.54GB | ~10GB | Original- | Full precision alternative | [Download](https://huggingface.co/mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/resolve/main/llama-joycaption-beta-one-hf-llava.Q8_0.gguf) |
103
+ | JoyCaption Beta One (F16) | 16.1GB | ~18GB | Original | Full precision (24GB+) | [Download](https://huggingface.co/mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/resolve/main/llama-joycaption-beta-one-hf-llava.f16.gguf) |
104
+
105
+ #### Alternative GGUF Sources
106
+ | Model | Size | Source | Link |
107
+ | ----- | ---- | ------ | ---- |
108
+ | JoyCaption Beta One (Q4_K) | 4.92GB | concedo | [Download](https://huggingface.co/concedo/llama-joycaption-beta-one-hf-llava-mmproj-gguf/resolve/main/Llama-Joycaption-Beta-One-Hf-Llava-Q4_K.gguf) |
109
+ | JoyCaption Beta One (Q8_0) | 8.54GB | concedo | [Download](https://huggingface.co/concedo/llama-joycaption-beta-one-hf-llava-mmproj-gguf/resolve/main/Llama-Joycaption-Beta-One-Hf-Llava-Q8_0.gguf) |
110
+ | JoyCaption Beta One (F16) | 16.1GB | concedo | [Download](https://huggingface.co/concedo/llama-joycaption-beta-one-hf-llava-mmproj-gguf/resolve/main/Llama-Joycaption-Beta-One-Hf-Llava-F16.gguf) |
111
+
112
+ **Note**: GGUF models also require the vision projection model:
113
+ - [llama-joycaption-beta-one-llava-mmproj-model-f16.gguf](https://huggingface.co/concedo/llama-joycaption-beta-one-hf-llava-mmproj-gguf/resolve/main/llama-joycaption-beta-one-llava-mmproj-model-f16.gguf)
114
+
115
+ After downloading, place the model files in your `ComfyUI/models/LLM/GGUF` directory.
116
+
117
+ ## Basic Usage
118
+
119
+ ### Standard Nodes (HuggingFace Models)
120
+
121
+ #### Basic Node
122
+ 1. Add the "JoyCaption" node from the `🧪AILab/📝JoyCaption` category
123
+ 2. Connect an image source to the node
124
+ 3. Select the model file (defaults to `llama-joycaption-beta-one-hf-llava`)
125
+ 4. Adjust the parameters as needed
126
+ 5. Run the workflow
127
+
128
+ #### Advanced Node
129
+ 1. Add the "JoyCaption (Advanced)" node from the `🧪AILab/📝JoyCaption` category
130
+ 2. Connect an image source to the node
131
+ 3. Select the caption type
132
+ 4. Adjust the parameters as needed
133
+ 5. Run the workflow
134
+
135
+ ### GGUF Nodes (Recommended for Better Performance)
136
+
137
+ #### GGUF Basic Node
138
+ 1. Add the "JoyCaption GGUF" node from the `🧪AILab/📝JoyCaption-GGUF` category
139
+ 2. Connect an image source to the node
140
+ 3. Select the GGUF model (e.g., "JoyCaption Beta One (IQ4_XS)")
141
+ 4. Choose processing mode (GPU/CPU)
142
+ 5. Select caption style and length
143
+ 6. Run the workflow
144
+
145
+ #### GGUF Advanced Node
146
+ 1. Add the "JoyCaption GGUF (Advanced)" node from the `🧪AILab/📝JoyCaption-GGUF` category
147
+ 2. Connect an image source to the node
148
+ 3. Configure all generation parameters (temperature, top_p, top_k, etc.)
149
+ 4. Set custom prompts if needed
150
+ 5. Run the workflow
151
+
152
+ ## Caption Tools
153
+
154
+ ### Image Batch Path 🖼️
155
+
156
+ This node allows you to load multiple images from a directory for batch processing:
157
+
158
+ | Parameter | Description |
159
+ | --------- | ----------- |
160
+ | **image_dir** | Directory path containing images |
161
+ | **batch_size** | Number of images to load (0 = all images) |
162
+ | **start_from** | Start from Nth image (1 = first image) |
163
+ | **sort_method** | Image loading order: sequential/reverse/random |
164
+
165
+ ### Caption Saver 📝
166
+
167
+ This node saves generated captions to text files:
168
+
169
+ | Parameter | Description |
170
+ | --------- | ----------- |
171
+ | **string** | Caption text to save |
172
+ | **image_path** | Path to the image being captioned |
173
+ | **image** | (Optional) Image to save alongside the caption |
174
+ | **custom_output_path** | (Optional) Custom output directory path |
175
+ | **custom_file_name** | (Optional) Custom filename (without extension) |
176
+ | **overwrite** | If true, will overwrite existing files; if false, will add a number to make the filename unique |
177
+
178
+ ### Parameters
179
+
180
+ #### Standard Nodes
181
+
182
+ ##### Basic Node
183
+ | Parameter | Description | Default | Range |
184
+ | --------- | ----------- | ------- | ----- |
185
+ | **Model** | The JoyCaption model to use | `llama-joycaption-beta-one-hf-llava` | - |
186
+ | **Memory Control** | Memory optimization settings | Default | Default (fp32), Balanced (8-bit), Maximum Savings (4-bit) |
187
+ | **Caption Type** | Caption style selection | Descriptive | Descriptive, Descriptive (Casual), Straightforward, Tags, Technical, Artistic |
188
+ | **Caption Length** | Output length control | medium | any, very short, short, medium, long, very long |
189
+
190
+ #### GGUF Nodes
191
+
192
+ ##### GGUF Basic Node
193
+ | Parameter | Description | Default | Range |
194
+ | --------- | ----------- | ------- | ----- |
195
+ | **Model** | GGUF model to use | JoyCaption Beta One (IQ4_XS) | Q2_K, IQ4_XS, Q5_K_M, Q6_K |
196
+ | **Processing Mode** | Hardware acceleration | GPU | GPU, CPU |
197
+ | **Caption Type** | Caption style selection | Descriptive | Descriptive, Descriptive (Casual), Straightforward, Tags, Technical, Artistic |
198
+ | **Caption Length** | Output length control | any | any, very short, short, medium, long, very long |
199
+ | **Memory Management** | Model memory handling | Keep in Memory | Keep in Memory, Clear After Run, Global Cache |
200
+
201
+ ##### GGUF Advanced Node
202
+ | Parameter | Description | Default | Range |
203
+ | --------- | ----------- | ------- | ----- |
204
+ | **Model** | GGUF model to use | JoyCaption Beta One (IQ4_XS) | Q2_K, IQ4_XS, Q5_K_M, Q6_K |
205
+ | **Processing Mode** | Hardware acceleration | GPU | GPU, CPU |
206
+ | **Max New Tokens** | Maximum tokens to generate | 512 | 1-2048 |
207
+ | **Temperature** | Generation randomness | 0.6 | 0.0-2.0 |
208
+ | **Top-p** | Nucleus sampling | 0.9 | 0.0-1.0 |
209
+ | **Top-k** | Top-k sampling | 0 | 0-100 |
210
+ | **Custom Prompt** | Custom prompt template | "" | Any text |
211
+ | **Memory Management** | Model memory handling | Keep in Memory | Keep in Memory, Clear After Run, Global Cache |
212
+
213
+
214
+ ### Quantization Options
215
+
216
+ #### Standard Models (HuggingFace)
217
+ | Mode | Precision | Memory Usage | Speed | Quality | Recommended GPU |
218
+ |------|-----------|--------------|-------|---------|----------------|
219
+ | Default | fp32 | ~16GB | 1x | Best | 24GB+ |
220
+ | Default | bf16 | ~8GB | 1.5x | Excellent | 16GB+ |
221
+ | Default | fp16 | ~8GB | 2x | Very Good | 16GB+ |
222
+ | Balanced | 8-bit | ~4GB | 2.5x | Good | 12GB+ |
223
+ | Maximum Savings | 4-bit | ~2GB | 3x | Acceptable | 8GB+ |
224
+
225
+ #### GGUF Models (Recommended)
226
+ | Quantization | Model Size | Memory Usage | Speed | Quality | Recommended GPU |
227
+ |-------------|------------|--------------|-------|---------|----------------|
228
+ | Q2_K | 3.18GB | ~4GB | 4x | Good | 6GB+ |
229
+ | Q3_K_S | 3.66GB | ~5GB | 3.5x | Good+ | 8GB+ |
230
+ | Q3_K_M | 4.02GB | ~5GB | 3.5x | Better | 8GB+ |
231
+ | Q3_K_L | 4.32GB | ~6GB | 3x | Better+ | 8GB+ |
232
+ | IQ4_XS | 4.48GB | ~6GB | 3x | Very Good | 8GB+ |
233
+ | Q4_K_S | 4.69GB | ~6GB | 3x | Very Good | 8GB+ |
234
+ | Q4_K_M | 4.92GB | ~7GB | 2.5x | Very Good+ | 10GB+ |
235
+ | Q5_K_S | 5.60GB | ~7GB | 2.5x | Excellent | 10GB+ |
236
+ | Q5_K_M | 5.73GB | ~8GB | 2.5x | Excellent+ | 12GB+ |
237
+ | Q6_K | 6.60GB | ~8GB | 2x | Near Original | 12GB+ |
238
+ | Q8_0 | 8.54GB | ~10GB | 1.8x | Original- | 16GB+ |
239
+ | F16 | 16.1GB | ~18GB | 1.5x | Original | 24GB+ |
240
+
241
+ **Note**: GGUF models provide better performance and lower memory usage compared to standard models. IQ4_XS offers the best balance of quality and efficiency.
242
+
243
+ #### Advanced Node
244
+
245
+ | Parameter | Description | Default | Range |
246
+ | --------- | ----------- | ------- | ----- |
247
+ | **Extra Options** | Additional feature options | [] | Multiple options |
248
+ | **Person Name** | Name for person descriptions | "" | Any text |
249
+ | **Max New Tokens** | Maximum tokens to generate | 512 | 1-2048 |
250
+ | **Temperature** | Generation temperature | 0.6 | 0.0-2.0 |
251
+ | **Top-p** | Sampling parameter | 0.9 | 0.0-1.0 |
252
+ | **Top-k** | Top-k sampling | 0 | 0-100 |
253
+ | **Precision** | Use fp32 for best quality, bf16 for balanced performance, fp16 for maximum speed. 8-bit and 4-bit quantization provide significant memory savings with minimal quality impact |
254
+
255
+ ### Memory Management Options
256
+
257
+ | Mode | Description | Recommended Use |
258
+ |------|-------------|-----------------|
259
+ | Global Cache | Keeps model in memory for fastest processing | High VRAM GPUs (16GB+) |
260
+ | Keep in Memory | Maintains model in memory until workflow ends | Medium VRAM GPUs (8GB+) |
261
+ | Clear After Run | Clears model after each generation | Low VRAM GPUs (<8GB) |
262
+
263
+ ## Setting Tips
264
+
265
+ | Setting | Recommendation |
266
+ | ------- | -------------- |
267
+ | **Model Choice** | Use GGUF models for better performance and lower memory usage. IQ4_XS offers the best balance of quality and efficiency |
268
+ | **Memory Mode** | Based on GPU VRAM: 24GB+ use Global Cache, 12GB+ use Keep in Memory, 8GB+ use Clear After Run |
269
+ | **Processing Mode** | Use GPU mode for faster processing, CPU mode for systems with limited VRAM |
270
+ | **Input Resolution** | The model works best with images of 512x512 or higher resolution |
271
+ | **Memory Usage** | If you encounter memory issues, try GGUF Q2_K model or use Clear After Run mode |
272
+ | **Performance** | For batch processing, consider using Global Cache mode with GGUF models if you have sufficient VRAM |
273
+ | **Temperature** | Lower values (0.6-0.7) for more stable results, higher values (0.8-1.0) for more diverse results |
274
+ | **Top-k Parameter** | Set to 0 to disable, or use values like 40-50 for more focused generation |
275
+
276
+ ## About Model
277
+
278
+ This implementation uses LLaVA-based image captioning models, optimized to provide fast and accurate image descriptions.
279
+
280
+ Model features:
281
+ * Free and open weights
282
+ * Uncensored content coverage
283
+ * Broad style diversity (digital art, photoreal, anime, etc.)
284
+ * Fast processing with bfloat16 precision
285
+ * High-quality caption generation
286
+ * Memory-efficient operation
287
+ * Consistent results across various image types
288
+ * Support for multiple caption styles
289
+ * Optimized for training diffusion models
290
+
291
+ The models are trained on diverse datasets, ensuring:
292
+ * Balanced representation across different image types
293
+ * High accuracy in various scenarios
294
+ * Robust performance with complex scenes
295
+ * Support for both SFW and NSFW content
296
+ * Equal coverage of different styles and concepts
297
+
298
+ ## Roadmap
299
+
300
+ ### ✅ Completed (v1.3.0)
301
+ * ✅ GGUF model support for better performance
302
+ * ✅ Support for 12 GGUF quantization formats (Q2_K to F16)
303
+ * ✅ Enhanced error handling and parameter validation
304
+ * ✅ Clean console output (no debug spam)
305
+ * ✅ Improved memory management options
306
+ * ✅ Batch processing support (Caption Tools)
307
+ * ✅ Performance optimizations for CPU processing (GGUF CPU mode)
308
+ * ✅ Enhanced batch processing features with memory management
309
+
310
+ ### 🔄 Future Plans
311
+ * More caption style options and custom prompts
312
+ * Advanced fine-tuning support for custom models
313
+ * Real-time processing optimizations
314
+ * Multi-language caption support
315
+ * Integration with more vision-language models
316
+
317
+ ## Credits
318
+
319
+ * **Original JoyCaption Model**: [fancyfeast](https://huggingface.co/fancyfeast) - Creator of the base JoyCaption models
320
+ * **GGUF Quantized Models**: [mradermacher](https://huggingface.co/mradermacher) - Provider of comprehensive GGUF quantized models (Q2_K to F16)
321
+ * **Alternative GGUF Models**: [concedo](https://huggingface.co/concedo) - Provider of alternative GGUF models with vision projection
322
+ * **ComfyUI Integration**: [1038lab](https://github.com/1038lab) - Developer of this ComfyUI custom node
323
+ * **LLaVA Framework**: Microsoft Research - Base vision-language model architecture
324
+ * **llama-cpp-python**: [abetlen](https://github.com/abetlen/llama-cpp-python) - Python bindings for llama.cpp
325
+
326
+ ## License
327
+
328
+
329
+ This repository's code is released under the GPL-3.0 License.
330
+
331
+
332
+
333
+
334
+
ComfyUI-JoyCaption/README_ZH.md ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ComfyUI-JoyCaption
2
+
3
+ [English](README.md) | [简体中文](README_ZH.md)
4
+
5
+ ComfyUI 自定义节点,基于 LLaVA VLM 提供高级图像描述功能,支持自定义风格和内存优化推理。
6
+
7
+ ## 功能特点
8
+
9
+ - 简单友好的用户界面
10
+ - 支持多种描述类型
11
+ - 灵活的长度控制
12
+ - 内存优化选项
13
+ - **GGUF 模型支持** - 高效的量化模型,提供更好的性能和更低的内存使用
14
+ - **自动模型下载** - 首次使用时自动下载并正确重命名模型
15
+ - 支持多种描述类型
16
+ - 支持高级自定义选项
17
+ - 多种精度选项 (fp32, bf16, fp16, 8-bit, 4-bit)
18
+ - 增强的内存管理,支持全局缓存模式
19
+ - 干净的控制台输出(无调试垃圾信息)
20
+ - 强大的错误处理和参数验证
21
+ - **llama_cpp_install文件夹** - 完整的llama-cpp-python安装指南和自动化脚本
22
+
23
+ ## 安装
24
+
25
+ 1. 将此仓库克隆到您的 `ComfyUI/custom_nodes` 目录:
26
+ ```bash
27
+ cd ComfyUI/custom_nodes
28
+ git clone https://github.com/1038lab/ComfyUI-JoyCaption.git
29
+ ```
30
+
31
+ 2. 安装所需依赖:
32
+ ```bash
33
+ cd ComfyUI/custom_nodes/ComfyUI-JoyCaption
34
+ pip install -r requirements.txt
35
+ ```
36
+
37
+ 3. **GGUF模型(推荐)**: 安装支持CUDA的llama-cpp-python:
38
+ ```bash
39
+ # 选项1: 自动化安装(推荐)
40
+ python llama_cpp_install/llama_cpp_install.py
41
+
42
+ # 选项2: 手动安装
43
+ pip install -r requirements_gguf.txt
44
+ ```
45
+
46
+ **可用安装指南:**
47
+ - **English**: [llama_cpp_install/llama_cpp_install.md](llama_cpp_install/llama_cpp_install.md)
48
+ - **中文**: [llama_cpp_install/llama_cpp_install_zh.md](llama_cpp_install/llama_cpp_install_zh.md)
49
+
50
+ ## 下载模型
51
+ 模型将在首次使用时自动下载并重命名,或者您可以手动下载:
52
+
53
+ ### 标准模型(HuggingFace 格式)
54
+ | 模型 | 链接 | 内存使用 |
55
+ | ----- | ---- | ------------ |
56
+ | JoyCaption Beta One | [下载](https://huggingface.co/fancyfeast/llama-joycaption-beta-one-hf-llava) | ~8-16GB |
57
+ | JoyCaption Alpha Two | [下载](https://huggingface.co/fancyfeast/llama-joycaption-alpha-two-hf-llava) | ~8-16GB |
58
+
59
+ ### GGUF 模型(量化,推荐)
60
+ | 模型 | 大小 | 内存使用 | 质量 | 推荐用途 | 链接 |
61
+ | ----- | ---- | ------------ | ------- | --------------- | ---- |
62
+ | JoyCaption Beta One (Q2_K) | 3.18GB | ~4GB | 良好 | 低显存 (6GB+) | [下载](https://huggingface.co/mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/resolve/main/llama-joycaption-beta-one-hf-llava.Q2_K.gguf) |
63
+ | JoyCaption Beta One (Q3_K_S) | 3.66GB | ~5GB | 良好+ | 预算系统 (8GB+) | [下载](https://huggingface.co/mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/resolve/main/llama-joycaption-beta-one-hf-llava.Q3_K_S.gguf) |
64
+ | JoyCaption Beta One (Q3_K_M) | 4.02GB | ~5GB | 更好 | 平衡性能 | [下载](https://huggingface.co/mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/resolve/main/llama-joycaption-beta-one-hf-llava.Q3_K_M.gguf) |
65
+ | JoyCaption Beta One (Q3_K_L) | 4.32GB | ~6GB | 更好+ | 质量/大小平衡 | [下载](https://huggingface.co/mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/resolve/main/llama-joycaption-beta-one-hf-llava.Q3_K_L.gguf) |
66
+ | JoyCaption Beta One (IQ4_XS) | 4.48GB | ~6GB | 很好 | **推荐** (8GB+) | [下载](https://huggingface.co/mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/resolve/main/llama-joycaption-beta-one-hf-llava.IQ4_XS.gguf) |
67
+ | JoyCaption Beta One (Q4_K_S) | 4.69GB | ~6GB | 很好 | 质量导向 | [下载](https://huggingface.co/mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/resolve/main/llama-joycaption-beta-one-hf-llava.Q4_K_S.gguf) |
68
+ | JoyCaption Beta One (Q4_K_M) | 4.92GB | ~7GB | 很好+ | 平衡选择 | [下载](https://huggingface.co/mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/resolve/main/llama-joycaption-beta-one-hf-llava.Q4_K_M.gguf) |
69
+ | JoyCaption Beta One (Q5_K_S) | 5.60GB | ~7GB | 优秀 | 高质量 (10GB+) | [下载](https://huggingface.co/mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/resolve/main/llama-joycaption-beta-one-hf-llava.Q5_K_S.gguf) |
70
+ | JoyCaption Beta One (Q5_K_M) | 5.73GB | ~8GB | 优秀+ | 高端质量 | [下载](https://huggingface.co/mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/resolve/main/llama-joycaption-beta-one-hf-llava.Q5_K_M.gguf) |
71
+ | JoyCaption Beta One (Q6_K) | 6.60GB | ~8GB | 接近原版 | 最高质量 (12GB+) | [下载](https://huggingface.co/mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/resolve/main/llama-joycaption-beta-one-hf-llava.Q6_K.gguf) |
72
+ | JoyCaption Beta One (Q8_0) | 8.54GB | ~10GB | 原版- | 全精度替代 | [下载](https://huggingface.co/mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/resolve/main/llama-joycaption-beta-one-hf-llava.Q8_0.gguf) |
73
+ | JoyCaption Beta One (F16) | 16.1GB | ~18GB | 原版 | 全精度 (24GB+) | [下载](https://huggingface.co/mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/resolve/main/llama-joycaption-beta-one-hf-llava.f16.gguf) |
74
+
75
+ #### 备选 GGUF 源
76
+ | 模型 | 大小 | 来源 | 链接 |
77
+ | ----- | ---- | ------ | ---- |
78
+ | JoyCaption Beta One (Q4_K) | 4.92GB | concedo | [下载](https://huggingface.co/concedo/llama-joycaption-beta-one-hf-llava-mmproj-gguf/resolve/main/Llama-Joycaption-Beta-One-Hf-Llava-Q4_K.gguf) |
79
+ | JoyCaption Beta One (Q8_0) | 8.54GB | concedo | [下载](https://huggingface.co/concedo/llama-joycaption-beta-one-hf-llava-mmproj-gguf/resolve/main/Llama-Joycaption-Beta-One-Hf-Llava-Q8_0.gguf) |
80
+ | JoyCaption Beta One (F16) | 16.1GB | concedo | [下载](https://huggingface.co/concedo/llama-joycaption-beta-one-hf-llava-mmproj-gguf/resolve/main/Llama-Joycaption-Beta-One-Hf-Llava-F16.gguf) |
81
+
82
+ **注意**:GGUF 模型还需要视觉投影模型:
83
+ - [llama-joycaption-beta-one-llava-mmproj-model-f16.gguf](https://huggingface.co/concedo/llama-joycaption-beta-one-hf-llava-mmproj-gguf/resolve/main/llama-joycaption-beta-one-llava-mmproj-model-f16.gguf)
84
+
85
+ 下载后,将模型文件放置在 `ComfyUI/models/LLM/GGUF` 目录中。
86
+
87
+ ## 基本使用
88
+
89
+ ### 标准节点(HuggingFace 模型)
90
+
91
+ #### 基础节点
92
+ 1. 从 `🧪AILab/📝JoyCaption` 类别添加 "JoyCaption" 节点
93
+ 2. 将图像源连接到节点
94
+ 3. 选择模型文件(默认为 `llama-joycaption-beta-one-hf-llava`)
95
+ 4. 根据需要调整参数
96
+ 5. 运行工作流
97
+
98
+ #### 高级节点
99
+ 1. 从 `🧪AILab/📝JoyCaption` 类别添加 "JoyCaption (Advanced)" 节点
100
+ 2. 将图像源连接到节点
101
+ 3. 选择描述类型
102
+ 4. 根据需要调整参数
103
+ 5. 运行工作流
104
+
105
+ ### GGUF 节点(推荐,性能更佳)
106
+
107
+ #### GGUF 基础节点
108
+ 1. 从 `🧪AILab/📝JoyCaption-GGUF` 类别添加 "JoyCaption GGUF" 节点
109
+ 2. 将图像源连接到节点
110
+ 3. 选择 GGUF 模型(例如 "JoyCaption Beta One (IQ4_XS)")
111
+ 4. 选择处理模式(GPU/CPU)
112
+ 5. 选择描述风格和长度
113
+ 6. 运行工作流
114
+
115
+ #### GGUF 高级节点
116
+ 1. 从 `🧪AILab/📝JoyCaption-GGUF` 类别添加 "JoyCaption GGUF (Advanced)" 节点
117
+ 2. 将图像源连接到节点
118
+ 3. 配置所有生成参数(temperature、top_p、top_k 等)
119
+ 4. 如需要可设置自定义提示
120
+ 5. 运行工作流
121
+
122
+ ## 描述工具
123
+
124
+ ### 图像批处理路径 🖼️
125
+
126
+ 此节点允许您从目录中加载多个图像进行批处理:
127
+
128
+ | 参数 | 描述 |
129
+ | --------- | ----------- |
130
+ | **image_dir** | 包含图像的目录路径 |
131
+ | **batch_size** | 要加载的图像数量(0 = 所有图像) |
132
+ | **start_from** | 从第N张图像开始(1 = 第一张图像) |
133
+ | **sort_method** | 图像加载顺序:顺序/倒序/随机 |
134
+
135
+ ### 描述保存器 📝
136
+
137
+ 此节点将生成的描述保存到文本文件:
138
+
139
+ | 参数 | 描述 |
140
+ | --------- | ----------- |
141
+ | **string** | 要保存的描述文本 |
142
+ | **image_path** | 被描述图像的路径 |
143
+ | **image** | (可选)要与描述一起保存的图像 |
144
+ | **custom_output_path** | (可选)自定义输出目录路径 |
145
+ | **custom_file_name** | (可选)自定义文件名(不带扩展名) |
146
+ | **overwrite** | 如果为true,将覆盖现有文件;如果为false,将添加数字使文件名唯一 |
147
+
148
+ ### 参数说明
149
+
150
+ #### 标准节点
151
+
152
+ ##### 基础节点
153
+ | 参数 | 描述 | 默认值 | 范围 |
154
+ | --------- | ----------- | ------- | ----- |
155
+ | **Model** | 使用的 JoyCaption 模型 | `llama-joycaption-beta-one-hf-llava` | - |
156
+ | **Memory Control** | 内存优化设置 | Default | Default (fp32), Balanced (8-bit), Maximum Savings (4-bit) |
157
+ | **Caption Type** | 描述风格选择 | Descriptive | Descriptive, Descriptive (Casual), Straightforward, Tags, Technical, Artistic |
158
+ | **Caption Length** | 输出长度控制 | medium | any, very short, short, medium, long, very long |
159
+
160
+ #### GGUF 节点
161
+
162
+ ##### GGUF 基础节点
163
+ | 参数 | 描述 | 默认值 | 范围 |
164
+ | --------- | ----------- | ------- | ----- |
165
+ | **Model** | 使用的 GGUF 模型 | JoyCaption Beta One (IQ4_XS) | Q2_K, IQ4_XS, Q5_K_M, Q6_K |
166
+ | **Processing Mode** | 硬件加速 | GPU | GPU, CPU |
167
+ | **Caption Type** | 描述风格选择 | Descriptive | Descriptive, Descriptive (Casual), Straightforward, Tags, Technical, Artistic |
168
+ | **Caption Length** | 输出长度控制 | any | any, very short, short, medium, long, very long |
169
+ | **Memory Management** | 模型内存处理 | Keep in Memory | Keep in Memory, Clear After Run, Global Cache |
170
+
171
+ ##### GGUF 高级节点
172
+ | 参数 | 描述 | 默认值 | 范围 |
173
+ | --------- | ----------- | ------- | ----- |
174
+ | **Model** | 使用的 GGUF 模型 | JoyCaption Beta One (IQ4_XS) | Q2_K, IQ4_XS, Q5_K_M, Q6_K |
175
+ | **Processing Mode** | 硬件加速 | GPU | GPU, CPU |
176
+ | **Max New Tokens** | 最大生成标记数 | 512 | 1-2048 |
177
+ | **Temperature** | 生成随机性 | 0.6 | 0.0-2.0 |
178
+ | **Top-p** | 核采样 | 0.9 | 0.0-1.0 |
179
+ | **Top-k** | Top-k 采样 | 0 | 0-100 |
180
+ | **Custom Prompt** | 自定义提示模板 | "" | 任意文本 |
181
+ | **Memory Management** | 模型内存处理 | Keep in Memory | Keep in Memory, Clear After Run, Global Cache |
182
+
183
+ ### 量化选项
184
+
185
+ #### 标准模型(HuggingFace���
186
+ | 模式 | 精度 | 内存使用 | 速度 | 质量 | 推荐 GPU |
187
+ |------|-----------|--------------|-------|---------|----------------|
188
+ | Default | fp32 | ~16GB | 1x | 最佳 | 24GB+ |
189
+ | Default | bf16 | ~8GB | 1.5x | 优秀 | 16GB+ |
190
+ | Default | fp16 | ~8GB | 2x | 很好 | 16GB+ |
191
+ | Balanced | 8-bit | ~4GB | 2.5x | 良好 | 12GB+ |
192
+ | Maximum Savings | 4-bit | ~2GB | 3x | 可接受 | 8GB+ |
193
+
194
+ #### GGUF 模型(推荐)
195
+ | 量化 | 模型大小 | 内存使用 | 速度 | 质量 | 推荐 GPU |
196
+ |-------------|------------|--------------|-------|---------|----------------|
197
+ | Q2_K | 3.18GB | ~4GB | 4x | 良好 | 6GB+ |
198
+ | Q3_K_S | 3.66GB | ~5GB | 3.5x | 良好+ | 8GB+ |
199
+ | Q3_K_M | 4.02GB | ~5GB | 3.5x | 更好 | 8GB+ |
200
+ | Q3_K_L | 4.32GB | ~6GB | 3x | 更好+ | 8GB+ |
201
+ | IQ4_XS | 4.48GB | ~6GB | 3x | 很好 | 8GB+ |
202
+ | Q4_K_S | 4.69GB | ~6GB | 3x | 很好 | 8GB+ |
203
+ | Q4_K_M | 4.92GB | ~7GB | 2.5x | 很好+ | 10GB+ |
204
+ | Q5_K_S | 5.60GB | ~7GB | 2.5x | 优秀 | 10GB+ |
205
+ | Q5_K_M | 5.73GB | ~8GB | 2.5x | 优秀+ | 12GB+ |
206
+ | Q6_K | 6.60GB | ~8GB | 2x | 接近原版 | 12GB+ |
207
+ | Q8_0 | 8.54GB | ~10GB | 1.8x | 原版- | 16GB+ |
208
+ | F16 | 16.1GB | ~18GB | 1.5x | 原版 | 24GB+ |
209
+
210
+ **注意**:GGUF 模型相比标准模型提供更好的性能和更低的内存使用。IQ4_XS 提供质量和效率的最佳平衡。
211
+
212
+ #### 高级节点
213
+
214
+ | 参数 | 描述 | 默认值 | 范围 |
215
+ | --------- | ----------- | ------- | ----- |
216
+ | **Extra Options** | 额外功能选项 | [] | 多个选项 |
217
+ | **Person Name** | 人物描述名称 | "" | 任意文本 |
218
+ | **Max New Tokens** | 最大生成标记数 | 512 | 1-2048 |
219
+ | **Temperature** | 生成温度 | 0.6 | 0.0-2.0 |
220
+ | **Top-p** | 采样参数 | 0.9 | 0.0-1.0 |
221
+ | **Top-k** | Top-k 采样 | 0 | 0-100 |
222
+
223
+ ### 内存管理选项
224
+
225
+ | 模式 | 描述 | 推荐使用 |
226
+ |------|-------------|-----------------|
227
+ | 全局缓存 | 将模型保持在内存中以获得最快的处理速度 | 高显存 GPU (16GB+) |
228
+ | 保持内存 | 在工作流结束前保持模型在内存中 | 中等显存 GPU (8GB+) |
229
+ | 运行后清除 | 每次生成后清除模型 | 低显存 GPU (<8GB) |
230
+
231
+ ## 设置建议
232
+
233
+ | 设置 | 建议 |
234
+ | ------- | -------------- |
235
+ | **模型选择** | 使用 GGUF 模型获得更好的性能和更低的内存使用。IQ4_XS 提供质量和效率的最佳平衡 |
236
+ | **内存模式** | 根据 GPU 显存:24GB+ 使用全局缓存,12GB+ 使用保持内存,8GB+ 使用运行后清除 |
237
+ | **处理模式** | 使用 GPU 模式获得更快处理速度,CPU 模式适用于显存有限的系统 |
238
+ | **输入分辨率** | 模型最适合 512x512 或更高分辨率的图像 |
239
+ | **内存使用** | 如果遇到内存问题,尝试 GGUF Q2_K 模型或使用运行后清除模式 |
240
+ | **性能** | 对于批处理,如果有足够的显存,考虑使用 GGUF 模型的全局缓存模式 |
241
+ | **Temperature** | 较低值 (0.6-0.7) 获得更稳定的结果,较高值 (0.8-1.0) 获得更多样化的结果 |
242
+ | **Top-k 参数** | 设置为 0 禁用,或使用 40-50 等值获得更集中的生成 |
243
+
244
+ ## 关于模型
245
+
246
+ 本实现使用基于 LLaVA 的图像描述模型,经过优化以提供快速准确的图像描述。
247
+
248
+ 模型特点:
249
+ * 免费开源权重
250
+ * 无内容审查限制
251
+ * 广泛的风格多样性(数字艺术、照片级真实感、动漫等)
252
+ * 使用 bfloat16 精度快速处理
253
+ * 高质量描述生成
254
+ * 内存高效运行
255
+ * 在各种图像类型上保持一致性
256
+ * 支持多种描述风格
257
+ * 针对扩散模型训练优化
258
+
259
+ 模型在多样化数据集上训练,确保:
260
+ * 不同图像类型的平衡表示
261
+ * 各种场景下的高准确性
262
+ * 复杂场景的稳健性能
263
+ * 支持 SFW 和 NSFW 内容
264
+ * 不同风格和概念的平等覆盖
265
+
266
+ ## 路线图
267
+
268
+ ### ✅ 已完成(v1.3.0)
269
+ * ✅ GGUF 模型支持,提供更好的性能
270
+ * ✅ 支持 12 种 GGUF 量化格式(Q2_K 到 F16)
271
+ * ✅ 增强的错误处理和参数验证
272
+ * ✅ 干净的控制台输出(无调试垃圾信息)
273
+ * ✅ 改进的内存管理选项
274
+ * ✅ 批处理支持(描述工具)
275
+ * ✅ CPU 处理性能优化(GGUF CPU 模式)
276
+ * ✅ 增强的批处理功能与内存管理
277
+
278
+ ### 🔄 未来计划
279
+ * 更多描述风格选项和自定义提示
280
+ * 高级微调支持自定义模型
281
+ * 实时处理优化
282
+ * 多语言描述支持
283
+ * 集成更多视觉-语言模型
284
+
285
+ ## 致谢
286
+
287
+ * **原始 JoyCaption 模型**: [fancyfeast](https://huggingface.co/fancyfeast) - 基础 JoyCaption 模型的创建者
288
+ * **GGUF 量化模型**: [mradermacher](https://huggingface.co/mradermacher) - 提供全面的 GGUF 量化模型 (Q2_K 到 F16)
289
+ * **备选 GGUF 模型**: [concedo](https://huggingface.co/concedo) - 提供带视觉投影的备选 GGUF 模型
290
+ * **ComfyUI 集成**: [1038lab](https://github.com/1038lab) - 此 ComfyUI 自定义节点的开发者
291
+ * **LLaVA 框架**: Microsoft Research - 基础视觉-语言模型架构
292
+ * **llama-cpp-python**: [abetlen](https://github.com/abetlen/llama-cpp-python) - llama.cpp 的 Python 绑定
293
+
294
+ ## 许可证
295
+
296
+ 本仓库代码基于 GPL-3.0 许可证发布。
297
+
298
+
299
+ 模型采用 GPL-3.0 许可证发布。请参阅 [LICENSE](LICENSE) 文件了解详情。
300
+
ComfyUI-JoyCaption/__init__.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import importlib
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ current_dir = Path(__file__).parent
7
+
8
+ if str(current_dir) not in sys.path:
9
+ sys.path.insert(0, str(current_dir))
10
+
11
+ NODE_CLASS_MAPPINGS = {}
12
+ NODE_DISPLAY_NAME_MAPPINGS = {}
13
+
14
+ EXCLUDE_FILES = ['__init__.py', '__pycache__']
15
+
16
+ # Enable Windows color support
17
+ if sys.platform == 'win32':
18
+ os.system('color')
19
+
20
+ # Check if llama-cpp-python is available for GGUF functionality
21
+ GGUF_AVAILABLE = False
22
+ try:
23
+ import llama_cpp
24
+ GGUF_AVAILABLE = True
25
+ except ImportError:
26
+ # Use Windows color codes for better visibility
27
+ print("\n" + "=" * 80)
28
+ print("\033[91mWARNING: llama-cpp-python library not found, GGUF functionality is not available\033[0m")
29
+ print("\033[93mTo use GGUF features, install additional dependencies:\033[0m")
30
+ print("\033[96mpip install -r requirements_gguf.txt\033[0m")
31
+
32
+ # Check if installation guide exists and provide link
33
+ install_guide = current_dir / "llama_cpp_install.md"
34
+ if install_guide.exists():
35
+ print("\033[93mFor detailed installation instructions with CUDA support, please see:\033[0m")
36
+ print(f"\033[96m{install_guide}\033[0m")
37
+
38
+ print("\033[92mBasic JoyCaption functionality is still available\033[0m")
39
+ print("=" * 80 + "\n")
40
+ except Exception as e:
41
+ print("\n" + "=" * 80)
42
+ print(f"\033[91mError loading GGUF dependencies: {str(e)}\033[0m")
43
+ print("\033[92mBasic JoyCaption functionality is still available\033[0m")
44
+ print("=" * 80 + "\n")
45
+
46
+ # Process all Python files in a deterministic order to avoid import-time races
47
+ for file in sorted(current_dir.glob('*.py')):
48
+ if file.name not in EXCLUDE_FILES:
49
+ try:
50
+ module_name = file.stem
51
+ spec = importlib.util.spec_from_file_location(module_name, str(file))
52
+ module = importlib.util.module_from_spec(spec)
53
+ sys.modules[module_name] = module
54
+
55
+ # Skip GGUF module if llama-cpp-python is not available
56
+ if not GGUF_AVAILABLE and module_name == 'JC_GGUF':
57
+ continue
58
+
59
+ spec.loader.exec_module(module)
60
+
61
+ if hasattr(module, 'NODE_CLASS_MAPPINGS'):
62
+ NODE_CLASS_MAPPINGS.update(module.NODE_CLASS_MAPPINGS)
63
+
64
+ if hasattr(module, 'NODE_DISPLAY_NAME_MAPPINGS'):
65
+ NODE_DISPLAY_NAME_MAPPINGS.update(module.NODE_DISPLAY_NAME_MAPPINGS)
66
+ except Exception as e:
67
+ print(f"Error loading module {module_name}: {str(e)}")
68
+ if module_name != 'JC_GGUF': # Only show warning for non-GGUF modules
69
+ print(f"Warning: Failed to load {module_name} module")
70
+
71
+ __all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS']
ComfyUI-JoyCaption/__pycache__/CaptionTools.cpython-310.pyc ADDED
Binary file (5.54 kB). View file
 
ComfyUI-JoyCaption/__pycache__/JC.cpython-310.pyc ADDED
Binary file (12.9 kB). View file
 
ComfyUI-JoyCaption/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.97 kB). View file
 
ComfyUI-JoyCaption/custom_models.md ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🧩 JoyCaption Custom Models Guide
2
+ Supports both **HF** and **GGUF** model customization.
3
+
4
+ ---
5
+
6
+ ## 💡 Overview
7
+ Starting from **JoyCaption v2.0.2**, users can register **their own models** —
8
+ without modifying any of the repository’s internal configuration files.
9
+
10
+ This makes it easy to:
11
+ - Test your own LLaVA / Phi / Qwen / Mistral etc. models
12
+ - Add new quantized GGUF models
13
+ - Keep your changes persistent between JoyCaption updates
14
+
15
+ ---
16
+
17
+ ## 📁 File Location
18
+ Create or edit this file in your JoyCaption directory:
19
+
20
+ ```
21
+
22
+ ComfyUI/custom_nodes/ComfyUI-JoyCaption/custom_models.json
23
+
24
+ ````
25
+
26
+ If the file doesn’t exist, JoyCaption will **skip it safely** (no errors).
27
+ You can also copy the provided `custom_models_example.json` and rename it.
28
+
29
+ ---
30
+
31
+ ## ⚙️ File Structure
32
+
33
+ ```json
34
+ {
35
+ "hf_models": {
36
+ "My-LLaVA-Model": {
37
+ "name": "myusername/llava-custom-model",
38
+ "description": "Example Hugging Face model for JoyCaption (HF format)."
39
+ }
40
+ },
41
+ "gguf_models": {
42
+ "My-GGUF-Caption-Model": {
43
+ "name": "myusername/llava-custom-gguf/model.gguf",
44
+ "description": "Example GGUF model with image captioning support."
45
+ }
46
+ }
47
+ }
48
+ ````
49
+
50
+ ### 🧱 Explanation
51
+
52
+ | Key | Description |
53
+ | ------------- | --------------------------------------------------------------------- |
54
+ | `hf_models` | Models loaded through HuggingFace / Transformers (used by `JC.py`) |
55
+ | `gguf_models` | Models using llama.cpp GGUF format (used by `JC_GGUF.py`) |
56
+ | `name` | Model identifier — either full HF repo path or local `.gguf` filename |
57
+ | `description` | Optional. Appears as tooltip in ComfyUI node interface |
58
+
59
+ ---
60
+
61
+ ## 🧩 Empty Default File
62
+
63
+ For users who haven’t added anything yet,
64
+ you can safely ship this minimal empty version in the repo:
65
+
66
+ ```json
67
+ {
68
+ "hf_models": {},
69
+ "gguf_models": {}
70
+ }
71
+ ```
72
+
73
+ If the file is empty or missing, JoyCaption will continue using built-in models.
74
+
75
+ ---
76
+
77
+ ## 🧱 Example Template
78
+
79
+ An example file `custom_models_example.json` is provided in the repository root:
80
+
81
+ ```json
82
+ {
83
+ "__comment__": "Example for user customization",
84
+ "hf_models": {
85
+ "My-Phi-Vision": {
86
+ "name": "myusername/phi-vision-captioner",
87
+ "description": "Custom Phi-based visual captioning model."
88
+ }
89
+ },
90
+ "gguf_models": {
91
+ "My-Gemma-GGUF": {
92
+ "name": "mlabonne/gemma-3-27b-it-abliterated-GGUF",
93
+ "description": "High-quality GGUF model for image captioning."
94
+ }
95
+ }
96
+ }
97
+ ```
98
+
99
+ Rename this file to `custom_models.json` to activate it.
100
+
101
+ ---
102
+
103
+ ## 🧰 Behavior Notes
104
+
105
+ * ✅ The system merges your `custom_models.json` entries with internal presets.
106
+ * ⚙️ The merging happens **at runtime** — no need to modify `jc_data.json`.
107
+ * 🧼 Safe: if parsing fails, JoyCaption prints a warning and continues running.
108
+ * 🔒 Your file is ignored during updates (no overwriting by git pulls).
109
+ * 🖥️ Works for both `JC.py` and `JC_GGUF.py` independently.
110
+
111
+ ---
112
+
113
+ ## 📘 Related Files
114
+
115
+ | File | Purpose |
116
+ | ---------------------------- | ------------------------------------------------ |
117
+ | `JC.py` | Handles HF-based models (e.g., LLaVA, Phi, Qwen) |
118
+ | `JC_GGUF.py` | Handles quantized GGUF models |
119
+ | `custom_models.json` | Your personal model definitions |
120
+ | `custom_models_example.json` | Example reference file |
121
+
122
+ ---
123
+
124
+ ## 🧠 Tips for Power Users
125
+
126
+ * You can define **multiple entries** under each section.
127
+ * Hugging Face repos can include **subfolders or filenames** if needed:
128
+
129
+ ```
130
+ "name": "myrepo/models/llava-custom-4bit/ggml-model-q4_k.gguf"
131
+ ```
132
+ * For local models, use the **relative path** under your `ComfyUI/models` directory.
133
+ * Descriptions are optional but highly recommended.
134
+
135
+ ---
136
+
137
+ ## 🪄 Troubleshooting
138
+
139
+ | Issue | Possible Cause | Fix |
140
+ | ------------------------------------------- | ----------------------------------------------------- | -------------------------------------------- |
141
+ | Model not showing in dropdown | JSON syntax error or missing section | Validate JSON format |
142
+ | “Failed to load custom_models.json” warning | Invalid JSON content | Check braces/quotes |
143
+ | Model loads but errors on inference | Wrong path or unsupported format | Verify `name` path and model type |
144
+ | GGUF model missing mmproj | Ensure `GGUF_SETTINGS["mmproj_filename"]` file exists | Download via `hf_hub_download` automatically |
145
+
146
+ ---
147
+
148
+ ## 🏁 Summary
149
+
150
+ ✅ **No internal edits needed**
151
+ ✅ **Both HF and GGUF supported**
152
+ ✅ **Safe and optional**
153
+ ✅ **Updatable without conflicts**
154
+
ComfyUI-JoyCaption/custom_models_example.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "hf_models": {
3
+ "__comment__": "For HuggingFace-format models (handled by JC.py). Each key appears in the dropdown list.",
4
+
5
+ "My-LLaVA-Model": {
6
+ "name": "myusername/llava-custom-model",
7
+ "description": "Example custom Hugging Face model with image captioning capability (LLaVA-based)."
8
+ },
9
+
10
+ "My-Phi-Vision": {
11
+ "name": "myusername/phi-vision-captioner",
12
+ "description": "Optional: a different HF model supporting visual-language tasks."
13
+ }
14
+ },
15
+
16
+ "gguf_models": {
17
+ "__comment__": "For GGUF-format models (handled by JC_GGUF.py). Each key appears in the GGUF model dropdown.",
18
+
19
+ "My-GGUF-Caption-Model": {
20
+ "name": "myusername/llava-custom-gguf-model/model.gguf",
21
+ "description": "Example GGUF model file from Hugging Face (must include correct mmproj if needed)."
22
+ },
23
+
24
+ "My-Gemma-GGUF": {
25
+ "name": "mlabonne/gemma-3-27b-it-abliterated-GGUF",
26
+ "description": "Example: large GGUF model known to work well with JoyCaption."
27
+ }
28
+ }
29
+ }
ComfyUI-JoyCaption/example_workflows/JoyCaption-GGUF.json ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "id": "6cdda1b6-9bfc-4b5f-9d6b-60ef9a9d93fc",
3
+ "revision": 0,
4
+ "last_node_id": 22,
5
+ "last_link_id": 26,
6
+ "nodes": [
7
+ {
8
+ "id": 16,
9
+ "type": "ImageBatchPath",
10
+ "pos": [
11
+ -611.5386352539062,
12
+ 298.06317138671875
13
+ ],
14
+ "size": [
15
+ 242.22389221191406,
16
+ 180
17
+ ],
18
+ "flags": {},
19
+ "order": 0,
20
+ "mode": 0,
21
+ "inputs": [],
22
+ "outputs": [
23
+ {
24
+ "name": "IMAGE",
25
+ "shape": 6,
26
+ "type": "IMAGE",
27
+ "links": [
28
+ 26
29
+ ]
30
+ },
31
+ {
32
+ "name": "IMAGE_PATH",
33
+ "shape": 6,
34
+ "type": "STRING",
35
+ "links": []
36
+ }
37
+ ],
38
+ "properties": {
39
+ "Node name for S&R": "ImageBatchPath"
40
+ },
41
+ "widgets_values": [
42
+ "O:\\images",
43
+ 1,
44
+ 2,
45
+ "sequential"
46
+ ]
47
+ },
48
+ {
49
+ "id": 19,
50
+ "type": "JC_GGUF",
51
+ "pos": [
52
+ 235.76669311523438,
53
+ 298.06317138671875
54
+ ],
55
+ "size": [
56
+ 298.5727233886719,
57
+ 174
58
+ ],
59
+ "flags": {},
60
+ "order": 2,
61
+ "mode": 0,
62
+ "inputs": [
63
+ {
64
+ "name": "image",
65
+ "type": "IMAGE",
66
+ "link": 20
67
+ },
68
+ {
69
+ "name": "extra_options",
70
+ "shape": 7,
71
+ "type": "JOYCAPTION_EXTRA_OPTIONS",
72
+ "link": null
73
+ }
74
+ ],
75
+ "outputs": [
76
+ {
77
+ "name": "STRING",
78
+ "type": "STRING",
79
+ "links": [
80
+ 22
81
+ ]
82
+ }
83
+ ],
84
+ "properties": {
85
+ "Node name for S&R": "JC_GGUF"
86
+ },
87
+ "widgets_values": [
88
+ "JoyCaption Beta One (IQ4_XS)",
89
+ "GPU",
90
+ "Descriptive",
91
+ "any",
92
+ "Keep in Memory"
93
+ ]
94
+ },
95
+ {
96
+ "id": 11,
97
+ "type": "PreviewAny",
98
+ "pos": [
99
+ 563.1483154296875,
100
+ 782.4658813476562
101
+ ],
102
+ "size": [
103
+ 551.0270385742188,
104
+ 254.4538116455078
105
+ ],
106
+ "flags": {},
107
+ "order": 6,
108
+ "mode": 0,
109
+ "inputs": [
110
+ {
111
+ "name": "source",
112
+ "type": "*",
113
+ "link": 24
114
+ }
115
+ ],
116
+ "outputs": [],
117
+ "properties": {
118
+ "cnr_id": "comfy-core",
119
+ "ver": "0.3.49",
120
+ "Node name for S&R": "PreviewAny"
121
+ },
122
+ "widgets_values": []
123
+ },
124
+ {
125
+ "id": 20,
126
+ "type": "JC_GGUF_adv",
127
+ "pos": [
128
+ 239.39669799804688,
129
+ 712.919677734375
130
+ ],
131
+ "size": [
132
+ 298.3599853515625,
133
+ 324
134
+ ],
135
+ "flags": {},
136
+ "order": 3,
137
+ "mode": 0,
138
+ "inputs": [
139
+ {
140
+ "name": "image",
141
+ "type": "IMAGE",
142
+ "link": 21
143
+ },
144
+ {
145
+ "name": "extra_options",
146
+ "shape": 7,
147
+ "type": "JOYCAPTION_EXTRA_OPTIONS",
148
+ "link": null
149
+ }
150
+ ],
151
+ "outputs": [
152
+ {
153
+ "name": "PROMPT",
154
+ "type": "STRING",
155
+ "links": [
156
+ 23
157
+ ]
158
+ },
159
+ {
160
+ "name": "STRING",
161
+ "type": "STRING",
162
+ "links": [
163
+ 24
164
+ ]
165
+ }
166
+ ],
167
+ "properties": {
168
+ "Node name for S&R": "JC_GGUF_adv"
169
+ },
170
+ "widgets_values": [
171
+ "JoyCaption Beta One (IQ4_XS)",
172
+ "GPU",
173
+ "Stable Diffusion Prompt",
174
+ "any",
175
+ 512,
176
+ 0.6,
177
+ 0.9,
178
+ 0,
179
+ "",
180
+ "Keep in Memory"
181
+ ]
182
+ },
183
+ {
184
+ "id": 17,
185
+ "type": "AILab_ImagePreview",
186
+ "pos": [
187
+ -348.1651306152344,
188
+ 298.06317138671875
189
+ ],
190
+ "size": [
191
+ 551.80078125,
192
+ 738.8565063476562
193
+ ],
194
+ "flags": {},
195
+ "order": 1,
196
+ "mode": 0,
197
+ "inputs": [
198
+ {
199
+ "name": "image",
200
+ "type": "IMAGE",
201
+ "link": 26
202
+ }
203
+ ],
204
+ "outputs": [
205
+ {
206
+ "name": "IMAGE",
207
+ "type": "IMAGE",
208
+ "links": [
209
+ 20,
210
+ 21
211
+ ]
212
+ }
213
+ ],
214
+ "properties": {
215
+ "cnr_id": "comfyui-rmbg",
216
+ "ver": "c36a6a819fef2208316693c29c055b5c558c89e8",
217
+ "Node name for S&R": "AILab_ImagePreview"
218
+ },
219
+ "widgets_values": [],
220
+ "color": "#2e3e57",
221
+ "bgcolor": "#4b5b73"
222
+ },
223
+ {
224
+ "id": 9,
225
+ "type": "PreviewAny",
226
+ "pos": [
227
+ 557.0983276367188,
228
+ 298.06317138671875
229
+ ],
230
+ "size": [
231
+ 546.5134887695312,
232
+ 241.1837158203125
233
+ ],
234
+ "flags": {},
235
+ "order": 4,
236
+ "mode": 0,
237
+ "inputs": [
238
+ {
239
+ "name": "source",
240
+ "type": "*",
241
+ "link": 22
242
+ }
243
+ ],
244
+ "outputs": [],
245
+ "properties": {
246
+ "cnr_id": "comfy-core",
247
+ "ver": "0.3.49",
248
+ "Node name for S&R": "PreviewAny"
249
+ },
250
+ "widgets_values": []
251
+ },
252
+ {
253
+ "id": 21,
254
+ "type": "PreviewAny",
255
+ "pos": [
256
+ 563.1483154296875,
257
+ 629.5003051757812
258
+ ],
259
+ "size": [
260
+ 385.2570495605469,
261
+ 88
262
+ ],
263
+ "flags": {},
264
+ "order": 5,
265
+ "mode": 0,
266
+ "inputs": [
267
+ {
268
+ "name": "source",
269
+ "type": "*",
270
+ "link": 23
271
+ }
272
+ ],
273
+ "outputs": [],
274
+ "properties": {
275
+ "cnr_id": "comfy-core",
276
+ "ver": "0.3.49",
277
+ "Node name for S&R": "PreviewAny"
278
+ },
279
+ "widgets_values": []
280
+ }
281
+ ],
282
+ "links": [
283
+ [
284
+ 20,
285
+ 17,
286
+ 0,
287
+ 19,
288
+ 0,
289
+ "IMAGE"
290
+ ],
291
+ [
292
+ 21,
293
+ 17,
294
+ 0,
295
+ 20,
296
+ 0,
297
+ "IMAGE"
298
+ ],
299
+ [
300
+ 22,
301
+ 19,
302
+ 0,
303
+ 9,
304
+ 0,
305
+ "*"
306
+ ],
307
+ [
308
+ 23,
309
+ 20,
310
+ 0,
311
+ 21,
312
+ 0,
313
+ "*"
314
+ ],
315
+ [
316
+ 24,
317
+ 20,
318
+ 1,
319
+ 11,
320
+ 0,
321
+ "*"
322
+ ],
323
+ [
324
+ 26,
325
+ 16,
326
+ 0,
327
+ 17,
328
+ 0,
329
+ "IMAGE"
330
+ ]
331
+ ],
332
+ "groups": [],
333
+ "config": {},
334
+ "extra": {
335
+ "ds": {
336
+ "scale": 0.8264462809917356,
337
+ "offset": [
338
+ 751.8155895059733,
339
+ 96.63700520386863
340
+ ]
341
+ },
342
+ "frontendVersion": "1.24.4"
343
+ },
344
+ "version": 0.4
345
+ }
ComfyUI-JoyCaption/example_workflows/Joycaption_node.json ADDED
@@ -0,0 +1,526 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "id": "00000000-0000-0000-0000-000000000000",
3
+ "revision": 0,
4
+ "last_node_id": 51,
5
+ "last_link_id": 77,
6
+ "nodes": [
7
+ {
8
+ "id": 39,
9
+ "type": "JC",
10
+ "pos": [
11
+ 1864.2611083984375,
12
+ 930
13
+ ],
14
+ "size": [
15
+ 290,
16
+ 150
17
+ ],
18
+ "flags": {},
19
+ "order": 3,
20
+ "mode": 0,
21
+ "inputs": [
22
+ {
23
+ "name": "image",
24
+ "type": "IMAGE",
25
+ "link": 68
26
+ },
27
+ {
28
+ "name": "extra_options",
29
+ "shape": 7,
30
+ "type": "JOYCAPTION_EXTRA_OPTIONS",
31
+ "link": 64
32
+ }
33
+ ],
34
+ "outputs": [
35
+ {
36
+ "name": "STRING",
37
+ "type": "STRING",
38
+ "links": [
39
+ 73
40
+ ]
41
+ }
42
+ ],
43
+ "properties": {
44
+ "enableTabs": false,
45
+ "tabWidth": 65,
46
+ "tabXOffset": 10,
47
+ "hasSecondTab": false,
48
+ "secondTabText": "Send Back",
49
+ "secondTabOffset": 80,
50
+ "secondTabWidth": 65,
51
+ "Node name for S&R": "JC",
52
+ "widget_ue_connectable": {}
53
+ },
54
+ "widgets_values": [
55
+ "joycaption-alpha-two",
56
+ "Balanced (8-bit)",
57
+ "Stable Diffusion Prompt",
58
+ "any"
59
+ ],
60
+ "color": "#233",
61
+ "bgcolor": "#355"
62
+ },
63
+ {
64
+ "id": 40,
65
+ "type": "JC_adv",
66
+ "pos": [
67
+ 1864.2611083984375,
68
+ 1260
69
+ ],
70
+ "size": [
71
+ 290,
72
+ 300
73
+ ],
74
+ "flags": {},
75
+ "order": 4,
76
+ "mode": 0,
77
+ "inputs": [
78
+ {
79
+ "name": "image",
80
+ "type": "IMAGE",
81
+ "link": 69
82
+ },
83
+ {
84
+ "name": "extra_options",
85
+ "shape": 7,
86
+ "type": "JOYCAPTION_EXTRA_OPTIONS",
87
+ "link": 65
88
+ }
89
+ ],
90
+ "outputs": [
91
+ {
92
+ "name": "PROMPT",
93
+ "type": "STRING",
94
+ "links": [
95
+ 74
96
+ ]
97
+ },
98
+ {
99
+ "name": "STRING",
100
+ "type": "STRING",
101
+ "links": [
102
+ 75
103
+ ]
104
+ }
105
+ ],
106
+ "properties": {
107
+ "enableTabs": false,
108
+ "tabWidth": 65,
109
+ "tabXOffset": 10,
110
+ "hasSecondTab": false,
111
+ "secondTabText": "Send Back",
112
+ "secondTabOffset": 80,
113
+ "secondTabWidth": 65,
114
+ "Node name for S&R": "JC_adv",
115
+ "widget_ue_connectable": {}
116
+ },
117
+ "widgets_values": [
118
+ "joycaption-beta-one",
119
+ "Balanced (8-bit)",
120
+ "Descriptive",
121
+ "very long",
122
+ 512,
123
+ 0.6,
124
+ 0.9,
125
+ 0,
126
+ ""
127
+ ],
128
+ "color": "#233",
129
+ "bgcolor": "#355"
130
+ },
131
+ {
132
+ "id": 41,
133
+ "type": "JC_ExtraOptions",
134
+ "pos": [
135
+ 1425.7388916015625,
136
+ 1024
137
+ ],
138
+ "size": [
139
+ 382.783203125,
140
+ 736
141
+ ],
142
+ "flags": {},
143
+ "order": 0,
144
+ "mode": 0,
145
+ "inputs": [],
146
+ "outputs": [
147
+ {
148
+ "name": "extra_options",
149
+ "type": "JOYCAPTION_EXTRA_OPTIONS",
150
+ "links": [
151
+ 64,
152
+ 65
153
+ ]
154
+ }
155
+ ],
156
+ "properties": {
157
+ "enableTabs": false,
158
+ "tabWidth": 65,
159
+ "tabXOffset": 10,
160
+ "hasSecondTab": false,
161
+ "secondTabText": "Send Back",
162
+ "secondTabOffset": 80,
163
+ "secondTabWidth": 65,
164
+ "Node name for S&R": "JC_ExtraOptions",
165
+ "widget_ue_connectable": {}
166
+ },
167
+ "widgets_values": [
168
+ false,
169
+ false,
170
+ false,
171
+ false,
172
+ false,
173
+ false,
174
+ false,
175
+ false,
176
+ false,
177
+ false,
178
+ false,
179
+ false,
180
+ false,
181
+ false,
182
+ false,
183
+ false,
184
+ false,
185
+ false,
186
+ false,
187
+ false,
188
+ false,
189
+ false,
190
+ false,
191
+ false,
192
+ false,
193
+ false,
194
+ true,
195
+ "Amy"
196
+ ],
197
+ "color": "#232",
198
+ "bgcolor": "#353"
199
+ },
200
+ {
201
+ "id": 42,
202
+ "type": "AILab_LoadImage",
203
+ "pos": [
204
+ 1020,
205
+ 930
206
+ ],
207
+ "size": [
208
+ 350,
209
+ 830
210
+ ],
211
+ "flags": {},
212
+ "order": 1,
213
+ "mode": 0,
214
+ "inputs": [],
215
+ "outputs": [
216
+ {
217
+ "name": "IMAGE",
218
+ "type": "IMAGE",
219
+ "links": [
220
+ 67
221
+ ]
222
+ },
223
+ {
224
+ "name": "MASK",
225
+ "type": "MASK",
226
+ "links": null
227
+ },
228
+ {
229
+ "name": "MASK_IMAGE",
230
+ "type": "IMAGE",
231
+ "links": null
232
+ },
233
+ {
234
+ "name": "WIDTH",
235
+ "type": "INT",
236
+ "links": null
237
+ },
238
+ {
239
+ "name": "HEIGHT",
240
+ "type": "INT",
241
+ "links": null
242
+ }
243
+ ],
244
+ "properties": {
245
+ "enableTabs": false,
246
+ "tabWidth": 65,
247
+ "tabXOffset": 10,
248
+ "hasSecondTab": false,
249
+ "secondTabText": "Send Back",
250
+ "secondTabOffset": 80,
251
+ "secondTabWidth": 65,
252
+ "cnr_id": "comfyui-rmbg",
253
+ "ver": "4faa7c7c12147db95345ee78b30f38273443ff99",
254
+ "widget_ue_connectable": {},
255
+ "Node name for S&R": "AILab_LoadImage"
256
+ },
257
+ "widgets_values": [
258
+ "ComfyUI_temp_jbrru_00003_.png",
259
+ "alpha",
260
+ 1,
261
+ "longest_side",
262
+ 0,
263
+ "image"
264
+ ]
265
+ },
266
+ {
267
+ "id": 43,
268
+ "type": "Reroute",
269
+ "pos": [
270
+ 1730,
271
+ 930
272
+ ],
273
+ "size": [
274
+ 75,
275
+ 26
276
+ ],
277
+ "flags": {},
278
+ "order": 2,
279
+ "mode": 0,
280
+ "inputs": [
281
+ {
282
+ "name": "",
283
+ "type": "*",
284
+ "link": 67
285
+ }
286
+ ],
287
+ "outputs": [
288
+ {
289
+ "name": "",
290
+ "type": "IMAGE",
291
+ "links": [
292
+ 68,
293
+ 69
294
+ ]
295
+ }
296
+ ],
297
+ "properties": {
298
+ "showOutputText": false,
299
+ "horizontal": false
300
+ }
301
+ },
302
+ {
303
+ "id": 47,
304
+ "type": "ShowText|pysssss",
305
+ "pos": [
306
+ 2210,
307
+ 930
308
+ ],
309
+ "size": [
310
+ 600,
311
+ 260
312
+ ],
313
+ "flags": {},
314
+ "order": 5,
315
+ "mode": 0,
316
+ "inputs": [
317
+ {
318
+ "name": "text",
319
+ "type": "STRING",
320
+ "link": 73
321
+ }
322
+ ],
323
+ "outputs": [
324
+ {
325
+ "name": "STRING",
326
+ "shape": 6,
327
+ "type": "STRING",
328
+ "links": []
329
+ }
330
+ ],
331
+ "properties": {
332
+ "enableTabs": false,
333
+ "tabWidth": 65,
334
+ "tabXOffset": 10,
335
+ "hasSecondTab": false,
336
+ "secondTabText": "Send Back",
337
+ "secondTabOffset": 80,
338
+ "secondTabWidth": 65,
339
+ "cnr_id": "comfyui-custom-scripts",
340
+ "ver": "aac13aa7ce35b07d43633c3bbe654a38c00d74f5",
341
+ "widget_ue_connectable": {},
342
+ "Node name for S&R": "ShowText|pysssss"
343
+ },
344
+ "widgets_values": [
345
+ "Photo of a young Asian woman walking barefoot on a city street at night, wearing a white t-shirt and high-waisted white shorts with a gold belt, short black hair, full body, long legs, slender physique, fair skin, urban setting, streetlights, blurry background, people walking, trees, plants in planters, casual attire, confident pose, high quality, jpeg artifacts"
346
+ ]
347
+ },
348
+ {
349
+ "id": 48,
350
+ "type": "ShowText|pysssss",
351
+ "pos": [
352
+ 2210,
353
+ 1260
354
+ ],
355
+ "size": [
356
+ 600,
357
+ 170
358
+ ],
359
+ "flags": {},
360
+ "order": 6,
361
+ "mode": 0,
362
+ "inputs": [
363
+ {
364
+ "name": "text",
365
+ "type": "STRING",
366
+ "link": 74
367
+ }
368
+ ],
369
+ "outputs": [
370
+ {
371
+ "name": "STRING",
372
+ "shape": 6,
373
+ "type": "STRING",
374
+ "links": []
375
+ }
376
+ ],
377
+ "properties": {
378
+ "enableTabs": false,
379
+ "tabWidth": 65,
380
+ "tabXOffset": 10,
381
+ "hasSecondTab": false,
382
+ "secondTabText": "Send Back",
383
+ "secondTabOffset": 80,
384
+ "secondTabWidth": 65,
385
+ "cnr_id": "comfyui-custom-scripts",
386
+ "ver": "aac13aa7ce35b07d43633c3bbe654a38c00d74f5",
387
+ "widget_ue_connectable": {},
388
+ "Node name for S&R": "ShowText|pysssss"
389
+ },
390
+ "widgets_values": [
391
+ "Write a very long detailed description for this image."
392
+ ]
393
+ },
394
+ {
395
+ "id": 49,
396
+ "type": "ShowText|pysssss",
397
+ "pos": [
398
+ 2210,
399
+ 1500
400
+ ],
401
+ "size": [
402
+ 600,
403
+ 260
404
+ ],
405
+ "flags": {},
406
+ "order": 7,
407
+ "mode": 0,
408
+ "inputs": [
409
+ {
410
+ "name": "text",
411
+ "type": "STRING",
412
+ "link": 75
413
+ }
414
+ ],
415
+ "outputs": [
416
+ {
417
+ "name": "STRING",
418
+ "shape": 6,
419
+ "type": "STRING",
420
+ "links": null
421
+ }
422
+ ],
423
+ "properties": {
424
+ "enableTabs": false,
425
+ "tabWidth": 65,
426
+ "tabXOffset": 10,
427
+ "hasSecondTab": false,
428
+ "secondTabText": "Send Back",
429
+ "secondTabOffset": 80,
430
+ "secondTabWidth": 65,
431
+ "cnr_id": "comfyui-custom-scripts",
432
+ "ver": "aac13aa7ce35b07d43633c3bbe654a38c00d74f5",
433
+ "widget_ue_connectable": {},
434
+ "Node name for S&R": "ShowText|pysssss"
435
+ },
436
+ "widgets_values": [
437
+ "The image is a photograph taken at night on a bustling urban sidewalk. The central subject is an Asian woman with a slim, toned physique and medium-sized breasts. She has straight, shoulder-length black hair with bangs, and her skin tone is light. She is wearing a simple, fitted white t-shirt and matching white high-waisted shorts that accentuate her long legs. She is barefoot, walking confidently down the sidewalk, her feet slightly apart.\n\nIn the background, the sidewalk is lined with people, some of whom are blurred, indicating motion. The people are dressed in casual summer clothing, including t-shirts, shorts, and backpacks. To the left, there is a black lamppost, and to the right, a wooden planter with green foliage. The background also features a mix of storefronts with illuminated signs and trees, adding a sense of depth and urban vibrancy to the scene. The lighting is soft and warm, with streetlights and neon signs creating a cozy, late-night atmosphere. The overall composition of the photograph emphasizes the woman's poised and confident presence amidst the busy cityscape. The textures in the image range from the smoothness of her clothing to the roughness of the sidewalk and the soft glow of the streetlights."
438
+ ]
439
+ }
440
+ ],
441
+ "links": [
442
+ [
443
+ 64,
444
+ 41,
445
+ 0,
446
+ 39,
447
+ 1,
448
+ "JOYCAPTION_EXTRA_OPTIONS"
449
+ ],
450
+ [
451
+ 65,
452
+ 41,
453
+ 0,
454
+ 40,
455
+ 1,
456
+ "JOYCAPTION_EXTRA_OPTIONS"
457
+ ],
458
+ [
459
+ 67,
460
+ 42,
461
+ 0,
462
+ 43,
463
+ 0,
464
+ "*"
465
+ ],
466
+ [
467
+ 68,
468
+ 43,
469
+ 0,
470
+ 39,
471
+ 0,
472
+ "IMAGE"
473
+ ],
474
+ [
475
+ 69,
476
+ 43,
477
+ 0,
478
+ 40,
479
+ 0,
480
+ "IMAGE"
481
+ ],
482
+ [
483
+ 73,
484
+ 39,
485
+ 0,
486
+ 47,
487
+ 0,
488
+ "STRING"
489
+ ],
490
+ [
491
+ 74,
492
+ 40,
493
+ 0,
494
+ 48,
495
+ 0,
496
+ "STRING"
497
+ ],
498
+ [
499
+ 75,
500
+ 40,
501
+ 1,
502
+ 49,
503
+ 0,
504
+ "STRING"
505
+ ]
506
+ ],
507
+ "groups": [],
508
+ "config": {},
509
+ "extra": {
510
+ "ds": {
511
+ "scale": 0.6830134553650705,
512
+ "offset": [
513
+ -175.6426170595139,
514
+ -471.9308396036945
515
+ ]
516
+ },
517
+ "ue_links": [],
518
+ "links_added_by_ue": [],
519
+ "frontendVersion": "1.19.9",
520
+ "VHS_latentpreview": false,
521
+ "VHS_latentpreviewrate": 0,
522
+ "VHS_MetadataImage": true,
523
+ "VHS_KeepIntermediate": true
524
+ },
525
+ "version": 0.4
526
+ }
ComfyUI-JoyCaption/example_workflows/batch_image_text_output.jpg ADDED
ComfyUI-JoyCaption/example_workflows/batch_image_text_output.json ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "id": "d7f22f6a-de79-4884-b925-2621f86c6dc6",
3
+ "revision": 0,
4
+ "last_node_id": 11,
5
+ "last_link_id": 11,
6
+ "nodes": [
7
+ {
8
+ "id": 3,
9
+ "type": "JC_adv",
10
+ "pos": [
11
+ 1043.3333740234375,
12
+ 0
13
+ ],
14
+ "size": [
15
+ 400,
16
+ 380
17
+ ],
18
+ "flags": {},
19
+ "order": 1,
20
+ "mode": 0,
21
+ "inputs": [
22
+ {
23
+ "name": "image",
24
+ "type": "IMAGE",
25
+ "link": 8
26
+ },
27
+ {
28
+ "name": "extra_options",
29
+ "shape": 7,
30
+ "type": "JOYCAPTION_EXTRA_OPTIONS",
31
+ "link": null
32
+ }
33
+ ],
34
+ "outputs": [
35
+ {
36
+ "name": "PROMPT",
37
+ "type": "STRING",
38
+ "links": []
39
+ },
40
+ {
41
+ "name": "STRING",
42
+ "type": "STRING",
43
+ "links": [
44
+ 6
45
+ ]
46
+ }
47
+ ],
48
+ "properties": {
49
+ "enableTabs": false,
50
+ "tabWidth": 65,
51
+ "tabXOffset": 10,
52
+ "hasSecondTab": false,
53
+ "secondTabText": "Send Back",
54
+ "secondTabOffset": 80,
55
+ "secondTabWidth": 65,
56
+ "Node name for S&R": "JC_adv",
57
+ "widget_ue_connectable": {}
58
+ },
59
+ "widgets_values": [
60
+ "joycaption-beta-one",
61
+ "Maximum Savings (4-bit)",
62
+ "Descriptive",
63
+ "short",
64
+ 512,
65
+ 0.6,
66
+ 0.9,
67
+ 0,
68
+ "",
69
+ "Keep in Memory"
70
+ ]
71
+ },
72
+ {
73
+ "id": 8,
74
+ "type": "CaptionSaver",
75
+ "pos": [
76
+ 1870,
77
+ -80
78
+ ],
79
+ "size": [
80
+ 400,
81
+ 200
82
+ ],
83
+ "flags": {},
84
+ "order": 4,
85
+ "mode": 0,
86
+ "inputs": [
87
+ {
88
+ "name": "string",
89
+ "type": "STRING",
90
+ "link": 7
91
+ },
92
+ {
93
+ "name": "image_path",
94
+ "type": "STRING",
95
+ "link": 5
96
+ },
97
+ {
98
+ "name": "image",
99
+ "shape": 7,
100
+ "type": "IMAGE",
101
+ "link": 11
102
+ }
103
+ ],
104
+ "outputs": [],
105
+ "properties": {
106
+ "enableTabs": false,
107
+ "tabWidth": 65,
108
+ "tabXOffset": 10,
109
+ "hasSecondTab": false,
110
+ "secondTabText": "Send Back",
111
+ "secondTabOffset": 80,
112
+ "secondTabWidth": 65,
113
+ "Node name for S&R": "CaptionSaver",
114
+ "widget_ue_connectable": {}
115
+ },
116
+ "widgets_values": [
117
+ "C:\\Images\\JC",
118
+ "JC_img",
119
+ false
120
+ ]
121
+ },
122
+ {
123
+ "id": 9,
124
+ "type": "ImageBatchPath",
125
+ "pos": [
126
+ 630,
127
+ -60
128
+ ],
129
+ "size": [
130
+ 400,
131
+ 200
132
+ ],
133
+ "flags": {},
134
+ "order": 0,
135
+ "mode": 0,
136
+ "inputs": [],
137
+ "outputs": [
138
+ {
139
+ "name": "IMAGE_PATH",
140
+ "shape": 6,
141
+ "type": "STRING",
142
+ "links": [
143
+ 5
144
+ ]
145
+ },
146
+ {
147
+ "name": "IMAGE",
148
+ "shape": 6,
149
+ "type": "IMAGE",
150
+ "links": [
151
+ 8,
152
+ 10
153
+ ]
154
+ }
155
+ ],
156
+ "properties": {
157
+ "enableTabs": false,
158
+ "tabWidth": 65,
159
+ "tabXOffset": 10,
160
+ "hasSecondTab": false,
161
+ "secondTabText": "Send Back",
162
+ "secondTabOffset": 80,
163
+ "secondTabWidth": 65,
164
+ "Node name for S&R": "ImageBatchPath",
165
+ "widget_ue_connectable": {}
166
+ },
167
+ "widgets_values": [
168
+ "C:\\Images",
169
+ 0,
170
+ 1,
171
+ "sequential"
172
+ ]
173
+ },
174
+ {
175
+ "id": 10,
176
+ "type": "ShowText|pysssss",
177
+ "pos": [
178
+ 1456.6666259765625,
179
+ 0
180
+ ],
181
+ "size": [
182
+ 400,
183
+ 380
184
+ ],
185
+ "flags": {},
186
+ "order": 3,
187
+ "mode": 0,
188
+ "inputs": [
189
+ {
190
+ "name": "text",
191
+ "type": "STRING",
192
+ "link": 6
193
+ }
194
+ ],
195
+ "outputs": [
196
+ {
197
+ "name": "STRING",
198
+ "shape": 6,
199
+ "type": "STRING",
200
+ "links": [
201
+ 7
202
+ ]
203
+ }
204
+ ],
205
+ "properties": {
206
+ "enableTabs": false,
207
+ "tabWidth": 65,
208
+ "tabXOffset": 10,
209
+ "hasSecondTab": false,
210
+ "secondTabText": "Send Back",
211
+ "secondTabOffset": 80,
212
+ "secondTabWidth": 65,
213
+ "cnr_id": "comfyui-custom-scripts",
214
+ "ver": "aac13aa7ce35b07d43633c3bbe654a38c00d74f5",
215
+ "Node name for S&R": "ShowText|pysssss",
216
+ "widget_ue_connectable": {}
217
+ },
218
+ "widgets_values": [
219
+ "Monochromatic digital drawing of a young woman with wavy, shoulder-length blonde hair, wearing a white collared shirt. She has a serene expression, large eyes, and subtle makeup. The background is a gradient grey, emphasizing her delicate features. The style is realistic with smooth textures and fine lines.",
220
+ "Digital grayscale portrait of a young woman with wavy, shoulder-length hair, light skin, and delicate features. She wears a simple necklace, long earrings, and a sleeveless top. Her expression is calm and confident, with subtle shadows enhancing her facial contours. The background is a smooth gradient.",
221
+ "Digital black-and-white portrait of a young, handsome man with short, slightly tousled hair, light stubble, and serious expression. He wears a collared shirt with visible buttons, set against a plain grey background. The detailed shading and realistic texture emphasize his facial features and subtle skin texture.",
222
+ "Realistic black-and-white digital portrait of an elderly man with wavy, gray hair, a trimmed beard, and deep wrinkles. He wears a collared shirt with a zip-up jacket. The background is a plain, light gray gradient. The detailed texture highlights his aged skin and expressive eyes, creating a lifelike, somber effect."
223
+ ]
224
+ },
225
+ {
226
+ "id": 11,
227
+ "type": "AILab_ImagePreview",
228
+ "pos": [
229
+ 1043.3333740234375,
230
+ -380
231
+ ],
232
+ "size": [
233
+ 810,
234
+ 330
235
+ ],
236
+ "flags": {},
237
+ "order": 2,
238
+ "mode": 0,
239
+ "inputs": [
240
+ {
241
+ "name": "image",
242
+ "type": "IMAGE",
243
+ "link": 10
244
+ }
245
+ ],
246
+ "outputs": [
247
+ {
248
+ "name": "IMAGE",
249
+ "type": "IMAGE",
250
+ "links": [
251
+ 11
252
+ ]
253
+ }
254
+ ],
255
+ "properties": {
256
+ "enableTabs": false,
257
+ "tabWidth": 65,
258
+ "tabXOffset": 10,
259
+ "hasSecondTab": false,
260
+ "secondTabText": "Send Back",
261
+ "secondTabOffset": 80,
262
+ "secondTabWidth": 65,
263
+ "cnr_id": "comfyui-rmbg",
264
+ "ver": "4faa7c7c12147db95345ee78b30f38273443ff99",
265
+ "Node name for S&R": "AILab_ImagePreview",
266
+ "widget_ue_connectable": {}
267
+ },
268
+ "widgets_values": [],
269
+ "color": "#2e3e57",
270
+ "bgcolor": "#4b5b73"
271
+ }
272
+ ],
273
+ "links": [
274
+ [
275
+ 5,
276
+ 9,
277
+ 0,
278
+ 8,
279
+ 1,
280
+ "STRING"
281
+ ],
282
+ [
283
+ 6,
284
+ 3,
285
+ 1,
286
+ 10,
287
+ 0,
288
+ "STRING"
289
+ ],
290
+ [
291
+ 7,
292
+ 10,
293
+ 0,
294
+ 8,
295
+ 0,
296
+ "STRING"
297
+ ],
298
+ [
299
+ 8,
300
+ 9,
301
+ 1,
302
+ 3,
303
+ 0,
304
+ "IMAGE"
305
+ ],
306
+ [
307
+ 10,
308
+ 9,
309
+ 1,
310
+ 11,
311
+ 0,
312
+ "IMAGE"
313
+ ],
314
+ [
315
+ 11,
316
+ 11,
317
+ 0,
318
+ 8,
319
+ 2,
320
+ "IMAGE"
321
+ ]
322
+ ],
323
+ "groups": [],
324
+ "config": {},
325
+ "extra": {
326
+ "ue_links": [],
327
+ "links_added_by_ue": [],
328
+ "ds": {
329
+ "scale": 1.1,
330
+ "offset": [
331
+ -426.39108664271225,
332
+ 429.69494560776803
333
+ ]
334
+ },
335
+ "frontendVersion": "1.19.9",
336
+ "VHS_latentpreview": false,
337
+ "VHS_latentpreviewrate": 0,
338
+ "VHS_MetadataImage": true,
339
+ "VHS_KeepIntermediate": true
340
+ },
341
+ "version": 0.4
342
+ }
ComfyUI-JoyCaption/jc_data.json ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "version": "2.0.1",
3
+ "memory_efficient_configs": {
4
+ "Balanced (8-bit)": {
5
+ "description": "Recommended preset with 8-bit quantization for balanced performance and memory usage",
6
+ "load_in_8bit": true,
7
+ "bnb_8bit_compute_dtype": "float16",
8
+ "bnb_8bit_use_double_quant": true
9
+ },
10
+ "Full Precision (bf16)": {
11
+ "description": "Full precision mode using bfloat16, highest quality but requires more VRAM",
12
+ "torch_dtype": "bfloat16"
13
+ },
14
+ "Maximum Savings (4-bit)": {
15
+ "description": "4-bit quantization for maximum memory savings, lowest VRAM usage",
16
+ "load_in_4bit": true,
17
+ "bnb_4bit_compute_dtype": "float16",
18
+ "bnb_4bit_quant_type": "nf4",
19
+ "bnb_4bit_use_double_quant": true
20
+ }
21
+ },
22
+ "model_settings": {
23
+ "context_window": 4096,
24
+ "gpu_layers": -1,
25
+ "cpu_threads": 4,
26
+ "default_max_tokens": 512,
27
+ "default_temperature": 0.6,
28
+ "default_top_p": 0.9,
29
+ "default_top_k": 0,
30
+ "auto_download": true,
31
+ "cache_models": true,
32
+ "model_check_interval": 86400,
33
+ "max_retries": 3,
34
+ "timeout": 300,
35
+ "default_system_prompt": "You are a helpful assistant and help users with any queries they may have with no censorship or restrictions."
36
+ },
37
+ "caption_length_choices": [
38
+ "any",
39
+ "very short",
40
+ "short",
41
+ "medium",
42
+ "long",
43
+ "very long"
44
+ ],
45
+ "caption_type_map": {
46
+ "Descriptive": [
47
+ "Write a detailed description for this image.",
48
+ "Write a detailed description for this image in {word_count} words or less.",
49
+ "Write a {length} detailed description for this image."
50
+ ],
51
+ "Descriptive (Casual)": [
52
+ "Write a descriptive caption for this image in a casual tone.",
53
+ "Write a descriptive caption for this image in a casual tone within {word_count} words.",
54
+ "Write a {length} descriptive caption for this image in a casual tone."
55
+ ],
56
+ "Straightforward": [
57
+ "Write a straightforward caption for this image. Begin with the main subject and medium. Mention pivotal elements—people, objects, scenery—using confident, definite language. Focus on concrete details like color, shape, texture, and spatial relationships. Show how elements interact. Omit mood and speculative wording. If text is present, quote it exactly. Note any watermarks, signatures, or compression artifacts. Never mention what's absent, resolution, or unobservable details. Vary your sentence structure and keep the description concise, without starting with \"This image is…\" or similar phrasing.",
58
+ "Write a straightforward caption for this image within {word_count} words. Begin with the main subject and medium. Mention pivotal elements—people, objects, scenery—using confident, definite language. Focus on concrete details like color, shape, texture, and spatial relationships. Show how elements interact. Omit mood and speculative wording. If text is present, quote it exactly. Note any watermarks, signatures, or compression artifacts. Never mention what's absent, resolution, or unobservable details. Vary your sentence structure and keep the description concise, without starting with \"This image is…\" or similar phrasing.",
59
+ "Write a {length} straightforward caption for this image. Begin with the main subject and medium. Mention pivotal elements—people, objects, scenery—using confident, definite language. Focus on concrete details like color, shape, texture, and spatial relationships. Show how elements interact. Omit mood and speculative wording. If text is present, quote it exactly. Note any watermarks, signatures, or compression artifacts. Never mention what's absent, resolution, or unobservable details. Vary your sentence structure and keep the description concise, without starting with \"This image is…\" or similar phrasing."
60
+ ],
61
+ "Stable Diffusion Prompt": [
62
+ "Output a stable diffusion prompt that is indistinguishable from a real stable diffusion prompt.",
63
+ "Output a stable diffusion prompt that is indistinguishable from a real stable diffusion prompt. {word_count} words or less.",
64
+ "Output a {length} stable diffusion prompt that is indistinguishable from a real stable diffusion prompt."
65
+ ],
66
+ "MidJourney": [
67
+ "Write a MidJourney prompt for this image.",
68
+ "Write a MidJourney prompt for this image within {word_count} words.",
69
+ "Write a {length} MidJourney prompt for this image."
70
+ ],
71
+ "Danbooru tag list": [
72
+ "Generate only comma-separated Danbooru tags (lowercase_underscores). Strict order: `artist:`, `copyright:`, `character:`, `meta:`, then general tags. Include counts (1girl), appearance, clothing, accessories, pose, expression, actions, background. Use precise Danbooru syntax. No extra text.",
73
+ "Generate only comma-separated Danbooru tags (lowercase_underscores). Strict order: `artist:`, `copyright:`, `character:`, `meta:`, then general tags. Include counts (1girl), appearance, clothing, accessories, pose, expression, actions, background. Use precise Danbooru syntax. No extra text. {word_count} words or less.",
74
+ "Generate only comma-separated Danbooru tags (lowercase_underscores). Strict order: `artist:`, `copyright:`, `character:`, `meta:`, then general tags. Include counts (1girl), appearance, clothing, accessories, pose, expression, actions, background. Use precise Danbooru syntax. No extra text. {length} length."
75
+ ],
76
+ "e621 tag list": [
77
+ "Write a comma-separated list of e621 tags in alphabetical order for this image. Start with the artist, copyright, character, species, meta, and lore tags (if any), prefixed by 'artist:', 'copyright:', 'character:', 'species:', 'meta:', and 'lore:'. Then all the general tags.",
78
+ "Write a comma-separated list of e621 tags in alphabetical order for this image. Start with the artist, copyright, character, species, meta, and lore tags (if any), prefixed by 'artist:', 'copyright:', 'character:', 'species:', 'meta:', and 'lore:'. Then all the general tags. Keep it under {word_count} words.",
79
+ "Write a {length} comma-separated list of e621 tags in alphabetical order for this image. Start with the artist, copyright, character, species, meta, and lore tags (if any), prefixed by 'artist:', 'copyright:', 'character:', 'species:', 'meta:', and 'lore:'. Then all the general tags."
80
+ ],
81
+ "Rule34 tag list": [
82
+ "Write a comma-separated list of rule34 tags in alphabetical order for this image. Start with the artist, copyright, character, and meta tags (if any), prefixed by 'artist:', 'copyright:', 'character:', and 'meta:'. Then all the general tags.",
83
+ "Write a comma-separated list of rule34 tags in alphabetical order for this image. Start with the artist, copyright, character, and meta tags (if any), prefixed by 'artist:', 'copyright:', 'character:', and 'meta:'. Then all the general tags. Keep it under {word_count} words.",
84
+ "Write a {length} comma-separated list of rule34 tags in alphabetical order for this image. Start with the artist, copyright, character, and meta tags (if any), prefixed by 'artist:', 'copyright:', 'character:', and 'meta:'. Then all the general tags."
85
+ ],
86
+ "Booru-like tag list": [
87
+ "Write a list of Booru-like tags for this image.",
88
+ "Write a list of Booru-like tags for this image within {word_count} words.",
89
+ "Write a {length} list of Booru-like tags for this image."
90
+ ],
91
+ "Art Critic": [
92
+ "Analyze this image like an art critic would with information about its composition, style, symbolism, the use of color, light, any artistic movement it might belong to, etc.",
93
+ "Analyze this image like an art critic would with information about its composition, style, symbolism, the use of color, light, any artistic movement it might belong to, etc. Keep it within {word_count} words.",
94
+ "Analyze this image like an art critic would with information about its composition, style, symbolism, the use of color, light, any artistic movement it might belong to, etc. Keep it {length}."
95
+ ],
96
+ "Product Listing": [
97
+ "Write a caption for this image as though it were a product listing.",
98
+ "Write a caption for this image as though it were a product listing. Keep it under {word_count} words.",
99
+ "Write a {length} caption for this image as though it were a product listing."
100
+ ],
101
+ "Social Media Post": [
102
+ "Write a caption for this image as if it were being used for a social media post.",
103
+ "Write a caption for this image as if it were being used for a social media post. Limit the caption to {word_count} words.",
104
+ "Write a {length} caption for this image as if it were being used for a social media post."
105
+ ]
106
+ },
107
+ "extra_options": {
108
+ "exclude_people_info": {
109
+ "name": "Exclude People Info",
110
+ "description": "Do NOT include information about people/characters that cannot be changed (like ethnicity, gender, etc), but do still include changeable attributes (like hair style).",
111
+ "default": false
112
+ },
113
+ "include_lighting": {
114
+ "name": "Include Lighting",
115
+ "description": "Include information about lighting.",
116
+ "default": false
117
+ },
118
+ "include_camera_angle": {
119
+ "name": "Include Camera Angle",
120
+ "description": "Include information about camera angle.",
121
+ "default": false
122
+ },
123
+ "include_watermark": {
124
+ "name": "Include Watermark",
125
+ "description": "Include information about whether there is a watermark or not.",
126
+ "default": false
127
+ },
128
+ "include_JPEG_artifacts": {
129
+ "name": "Include JPEG Artifacts",
130
+ "description": "Include information about whether there are JPEG artifacts or not.",
131
+ "default": false
132
+ },
133
+ "include_exif": {
134
+ "name": "Include EXIF",
135
+ "description": "If it is a photo you MUST include information about what camera was likely used and details such as aperture, shutter speed, ISO, etc.",
136
+ "default": false
137
+ },
138
+ "exclude_sexual": {
139
+ "name": "Exclude Sexual",
140
+ "description": "Do NOT include anything sexual; keep it PG.",
141
+ "default": false
142
+ },
143
+ "exclude_image_resolution": {
144
+ "name": "Exclude Image Resolution",
145
+ "description": "Do NOT mention the image's resolution.",
146
+ "default": false
147
+ },
148
+ "include_aesthetic_quality": {
149
+ "name": "Include Aesthetic Quality",
150
+ "description": "You MUST include information about the subjective aesthetic quality of the image from low to very high.",
151
+ "default": false
152
+ },
153
+ "include_composition_style": {
154
+ "name": "Include Composition Style",
155
+ "description": "Include information on the image's composition style, such as leading lines, rule of thirds, or symmetry.",
156
+ "default": false
157
+ },
158
+ "exclude_text": {
159
+ "name": "Exclude Text",
160
+ "description": "Do NOT mention any text that is in the image.",
161
+ "default": false
162
+ },
163
+ "specify_depth_field": {
164
+ "name": "Specify Depth Field",
165
+ "description": "Specify the depth of field and whether the background is in focus or blurred.",
166
+ "default": false
167
+ },
168
+ "specify_lighting_sources": {
169
+ "name": "Specify Lighting Sources",
170
+ "description": "If applicable, mention the likely use of artificial or natural lighting sources.",
171
+ "default": false
172
+ },
173
+ "do_not_use_ambiguous_language": {
174
+ "name": "Do Not Use Ambiguous Language",
175
+ "description": "Do NOT use any ambiguous language.",
176
+ "default": false
177
+ },
178
+ "include_nsfw": {
179
+ "name": "Include NSFW",
180
+ "description": "Include whether the image is sfw, suggestive, or nsfw.",
181
+ "default": false
182
+ },
183
+ "only_describe_most_important_elements": {
184
+ "name": "Only Describe Most Important Elements",
185
+ "description": "ONLY describe the most important elements of the image.",
186
+ "default": false
187
+ },
188
+ "do_not_include_artist_name_or_title": {
189
+ "name": "Do Not Include Artist Name or Title",
190
+ "description": "If it is a work of art, do not include the artist's name or the title of the work.",
191
+ "default": false
192
+ },
193
+ "identify_image_orientation": {
194
+ "name": "Identify Image Orientation",
195
+ "description": "Identify the image orientation (portrait, landscape, or square) and aspect ratio if obvious.",
196
+ "default": false
197
+ },
198
+ "use_vulgar_slang_and_profanity": {
199
+ "name": "Use Vulgar Slang and Profanity",
200
+ "description": "Use vulgar slang and profanity, such as (but not limited to) \"fucking,\" \"slut,\" \"cock,\" etc.",
201
+ "default": false
202
+ },
203
+ "do_not_use_polite_euphemisms": {
204
+ "name": "Do Not Use Polite Euphemisms",
205
+ "description": "Do NOT use polite euphemisms—lean into blunt, casual phrasing.",
206
+ "default": false
207
+ },
208
+ "include_character_age": {
209
+ "name": "Include Character Age",
210
+ "description": "Include information about the ages of any people/characters when applicable.",
211
+ "default": false
212
+ },
213
+ "include_camera_shot_type": {
214
+ "name": "Include Camera Shot Type",
215
+ "description": "Mention whether the image depicts an extreme close-up, close-up, medium close-up, medium shot, cowboy shot, medium wide shot, wide shot, or extreme wide shot.",
216
+ "default": false
217
+ },
218
+ "exclude_mood_feeling": {
219
+ "name": "Exclude Mood Feeling",
220
+ "description": "Do not mention the mood/feeling/etc of the image.",
221
+ "default": false
222
+ },
223
+ "include_camera_vantage_height": {
224
+ "name": "Include Camera Vantage Height",
225
+ "description": "Explicitly specify the vantage height (eye-level, low-angle worm's-eye, bird's-eye, drone, rooftop, etc.).",
226
+ "default": false
227
+ },
228
+ "mention_watermark": {
229
+ "name": "Mention Watermark",
230
+ "description": "If there is a watermark, you must mention it.",
231
+ "default": false
232
+ },
233
+ "avoid_meta_descriptive_phrases": {
234
+ "name": "Avoid Meta Descriptive Phrases",
235
+ "description": "Your response will be used by a text-to-image model, so avoid useless meta phrases like \"This image shows…\", \"You are looking at...\", etc.",
236
+ "default": false
237
+ },
238
+ "refer_character_name": {
239
+ "name": "Refer Character Name",
240
+ "description": "If there is a person/character in the image you must refer to them as {name}.",
241
+ "default": false
242
+ }
243
+ },
244
+ "gguf_settings": {
245
+ "mmproj_filename": "llama-joycaption-beta-one-llava-mmproj-model-f16.gguf",
246
+ "default_image_size": [336, 336]
247
+ },
248
+ "hf_models": {
249
+ "joycaption-beta-one-fp8": {
250
+ "name": "JKCHSTR/llama-joycaption-alpha-two-hf-llava-FP8-Dynamic",
251
+ "description": "JoyCaption Beta One - FP8 Dynamic Quantization of llama-joycaption-beta-one"
252
+ },
253
+ "joycaption-beta-one": {
254
+ "name": "1038lab/llama-joycaption-beta-one",
255
+ "description": "JoyCaption Beta One - Latest version with improved performance and quality"
256
+ },
257
+ "joycaption-alpha-two": {
258
+ "name": "1038lab/llama-joycaption-alpha-two",
259
+ "description": "JoyCaption Alpha Two - Previous version, still available for compatibility"
260
+ }
261
+ },
262
+ "gguf_models": {
263
+ "JoyCaption Beta One (IQ4_XS)": {
264
+ "name": "mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/llama-joycaption-beta-one-hf-llava.IQ4_XS.gguf",
265
+ "description": "4.48 GB - IQ4 Extra Small model"
266
+ },
267
+ "JoyCaption Beta One (Q2_K)": {
268
+ "name": "mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/llama-joycaption-beta-one-hf-llava.Q2_K.gguf",
269
+ "description": "3.18 GB - 2-bit K-quants model"
270
+ },
271
+ "JoyCaption Beta One (Q3_K_L)": {
272
+ "name": "mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/llama-joycaption-beta-one-hf-llava.Q3_K_L.gguf",
273
+ "description": "4.32 GB - 3-bit K-quants Large model"
274
+ },
275
+ "JoyCaption Beta One (Q3_K_M)": {
276
+ "name": "mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/llama-joycaption-beta-one-hf-llava.Q3_K_M.gguf",
277
+ "description": "4.02 GB - 3-bit K-quants Medium model"
278
+ },
279
+ "JoyCaption Beta One (Q3_K_S)": {
280
+ "name": "mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/llama-joycaption-beta-one-hf-llava.Q3_K_S.gguf",
281
+ "description": "3.66 GB - 3-bit K-quants Small model"
282
+ },
283
+ "JoyCaption Beta One (Q4_K_M)": {
284
+ "name": "mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/llama-joycaption-beta-one-hf-llava.Q4_K_M.gguf",
285
+ "description": "4.92 GB - 4-bit K-quants Medium model"
286
+ },
287
+ "JoyCaption Beta One (Q4_K_S)": {
288
+ "name": "mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/llama-joycaption-beta-one-hf-llava.Q4_K_S.gguf",
289
+ "description": "4.69 GB - 4-bit K-quants Small model"
290
+ },
291
+ "JoyCaption Beta One (Q5_K_M)": {
292
+ "name": "mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/llama-joycaption-beta-one-hf-llava.Q5_K_M.gguf",
293
+ "description": "5.73 GB - 5-bit K-quants Medium model"
294
+ },
295
+ "JoyCaption Beta One (Q5_K_S)": {
296
+ "name": "mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/llama-joycaption-beta-one-hf-llava.Q5_K_S.gguf",
297
+ "description": "5.6 GB - 5-bit K-quants Small model"
298
+ },
299
+ "JoyCaption Beta One (Q6_K)": {
300
+ "name": "mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/llama-joycaption-beta-one-hf-llava.Q6_K.gguf",
301
+ "description": "6.6 GB - 6-bit K-quants model"
302
+ },
303
+ "JoyCaption Beta One (Q8_0)": {
304
+ "name": "mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/llama-joycaption-beta-one-hf-llava.Q8_0.gguf",
305
+ "description": "8.54 GB - 8-bit base model"
306
+ },
307
+ "JoyCaption Beta One (F16)": {
308
+ "name": "mradermacher/llama-joycaption-beta-one-hf-llava-GGUF/llama-joycaption-beta-one-hf-llava.f16.gguf",
309
+ "description": "16.1 GB - Full precision F16 model"
310
+ },
311
+ "joycaption-beta-one-gguf-q4_k": {
312
+ "name": "concedo/llama-joycaption-beta-one-hf-llava-mmproj-gguf/Llama-Joycaption-Beta-One-Hf-Llava-Q4_K.gguf",
313
+ "description": "JoyCaption Beta One GGUF - Q4_K quantized model (4.92 GB)"
314
+ },
315
+ "joycaption-beta-one-gguf-q8_0": {
316
+ "name": "concedo/llama-joycaption-beta-one-hf-llava-mmproj-gguf/Llama-Joycaption-Beta-One-Hf-Llava-Q8_0.gguf",
317
+ "description": "JoyCaption Beta One GGUF - Q8_0 quantized model (8.54 GB)"
318
+ },
319
+ "joycaption-beta-one-gguf-f16": {
320
+ "name": "concedo/llama-joycaption-beta-one-hf-llava-mmproj-gguf/Llama-Joycaption-Beta-One-Hf-Llava-F16.gguf",
321
+ "description": "JoyCaption Beta One GGUF - F16 full precision model (16.1 GB)"
322
+ }
323
+ }
324
+
325
+ }
ComfyUI-JoyCaption/llama_cpp_install/llama_cpp_install.md ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # `llama-cpp-python` CUDA Installation for ComfyUI Portable
2
+
3
+ This guide helps you install `llama-cpp-python` with GPU (CUDA) support for ComfyUI's Windows portable version.
4
+
5
+ ---
6
+
7
+ ### **1. Open ComfyUI's Command Prompt**
8
+
9
+ * Go to `C:\ComfyUI_windows_portable\python_embeded`
10
+ * In the address bar, type `cmd` and press Enter.
11
+
12
+ ---
13
+
14
+ ### **2. Install Build Tools (If you haven't already)**
15
+
16
+ * **Install Visual Studio Build Tools:**
17
+ * Download from [https://visualstudio.microsoft.com/downloads/](https://visualstudio.microsoft.com/downloads/) (under "Tools for Visual Studio").
18
+ * Run installer, select **"Desktop development with C++"** workload.
19
+ * **Install NVIDIA CUDA Toolkit:**
20
+ * Download your CUDA version (e.g., 12.6) from [https://developer.nvidia.com/cuda-toolkit-archive](https://developer.nvidia.com/cuda-toolkit-archive).
21
+ * Run installer, ensure **"Visual Studio Integration"** is selected.
22
+
23
+ ## **Automatic Installation Script (Recommended)**
24
+
25
+ * Make sure the installation script is saved here:
26
+ `.\ComfyUI\custom_nodes\ComfyUI-JoyCaption\install_llama_official.py`
27
+
28
+ * In the command prompt (opened in step 1), run the script with:
29
+
30
+ ```bash
31
+ .\python_embeded\python.exe llama_cpp_install.py
32
+ ```
33
+
34
+ The script will:
35
+
36
+ * Upgrade pip
37
+ * Clear pip cache
38
+ * Install minimal build dependencies (scikit-build-core, cmake)
39
+ * Detect GPU and build llama-cpp-python with CUDA support if available
40
+
41
+ 🕒 This process may take 5–20+ minutes depending on your system.
42
+
43
+ ### ** Restart ComfyUI**
44
+
45
+ * Close ComfyUI.
46
+ * Restart ComfyUI.
47
+ * Hard refresh your browser with Ctrl+F5 (Windows) or Cmd+Shift+R (macOS).
48
+
49
+
50
+
51
+
52
+ ## **Manuelly Installation**
53
+ ---
54
+
55
+ ### **1. Prepare Python Environment**
56
+
57
+ * In the command prompt, run:
58
+ ```bash
59
+ .\python.exe -m pip install --upgrade pip
60
+ .\python.exe -m pip cache purge
61
+ .\python.exe -m pip install scikit-build-core cmake
62
+ ```
63
+
64
+ ---
65
+
66
+ ### **2. Compile and Install `llama-cpp-python`**
67
+
68
+ * In the command prompt, run:
69
+ ```bash
70
+ set CMAKE_ARGS="-DGGML_CUDA=on" && .\python.exe -m pip install llama-cpp-python --no-cache-dir && set CMAKE_ARGS=
71
+ ```
72
+ * **Wait patiently.** This takes time (5-20+ minutes).
73
+
74
+ ---
75
+
76
+ ### **3. Restart ComfyUI**
77
+
78
+ * Close ComfyUI.
79
+ * Restart ComfyUI.
80
+ * Hard refresh your web browser (`Ctrl+F5` or `Cmd+Shift+R`).
81
+
82
+ ---
83
+