First commit

This commit is contained in:
Jianqiao Huang
2025-08-31 12:35:21 -07:00
commit f1218d3cdb
9 changed files with 1025 additions and 0 deletions
+166
View File
@@ -0,0 +1,166 @@
*.bin
*.gguf
*.safetensors
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
.pdm.toml
.pdm-python
.pdm-build/
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+67
View File
@@ -0,0 +1,67 @@
# ComfyUI-UnetBnbModelLoader
BitsAndBytes 4bit Quantization (NF4/FP4) Unet Model Loader
ComfyUI has long had issues with support for the bnb 4-bit quantization model. At least the plugins I could find couldn't load most models released on HF. There were also various other issues, such as LoRA incompatibility.
The official NF4 plugin, https://github.com/comfyanonymous/ComfyUI_bitsandbytes_NF4, has been largely abandoned. Previous forks also have varying degrees of issues (model incompatibility or LoRa incompatibility).
The bnb 4-bit format has never been very popular in the community, and GGUF's plugin is very stable and easy to use. So it seems no one has truly developed a plugin with better compatibility.
I used to like GGUF, which offers a variety of model sizes. However, its inference speed is slightly slower, which is a significant issue for models requiring many inference steps.
So, I decided to develop a universal BnB 4-bit model loading plugin, hoping to provide the community with more options.
Features of this plugin:
1. Architecturally agnostic, it supports most popular model plugins(need to be diffusers model or can convert to diffusers model), such as Flux, HiDReam and Qwen-Image, as well as future models.
2. Supports loading sharded safetensors files. This is surprisingly easy to support, and I'm surprised why the standard official model loader doesn't support it, and why other plugins don't support it either.
3. Supports LoRa, with a dedicated dequantization process for LoRa. Perhaps this is the first truly usable BnB 4-bit plugin to support LoRa?
4. 4-bit inference: 4-bit inference is reasonably fast compare to GGUF.
5. On-the-fly dequantization ensures the small size of 4-bit models.
6. Support for independent layer precision allows us to support mixed-precision models.
7. Check if it is a bnb-4bit model when loading, if not fallback to the general unet loader.
## Installation
> [!IMPORTANT]
> Make sure your ComfyUI is on a recent-enough version to support custom ops when loading the UNET-only.
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 bitsandbytes`)
```
git clone https://github.com/mengqin/ComfyUI-UnetBnbModelLoader
```
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:
```
git clone https://github.com/mengqin/ComfyUI-UnetBnbModelLoader ComfyUI/custom_nodes/ComfyUI-UnetBnbModelLoader
.\python_embeded\python.exe -s -m pip install -r .\ComfyUI\custom_nodes\ComfyUI-UnetBnbModelLoader\requirements.txt
```
Because this plugin relies on bitsandbytes, we are unable to support macOS and AMD GPUs.
## Usage
After installation, double-click a blank space in comfyui, search for "Unet Bnb Model Loader," and select your model to use it. Please place your model in the unet or diffuser-models directory.
If your model is multi-sharded, remember to place all shards in the same directory and maintain the classic 0000n-of-0000m shard model name format. In our model drop-down list, multi-shard models will not display the specific model name, but the model directory instead.
Supported model files:
- [flux1-dev-bnb-nf4](https://huggingface.co/lllyasviel/flux1-dev-bnb-nf4)
- [Flux-Krea_bnb-nf4](https://huggingface.co/AcademiaSD/Flux-Krea_bnb-nf4)
- [flux1-schnell-nf4-v2](https://huggingface.co/duuuuuuuden/flux1-schnell-nf4-v2)
- [flux1-nf4-unet](https://huggingface.co/silveroxides/flux1-nf4-unet)
- [HiDream-I1-Fast-nf4](https://huggingface.co/azaneko/HiDream-I1-Fast-nf4)
- [HiDream-I1-Full-nf4](https://huggingface.co/azaneko/HiDream-I1-Full-nf4)
- [HiDream-I1-Dev-nf4](https://huggingface.co/azaneko/HiDream-I1-Dev-nf4)
- [qwen-image-4bit](https://huggingface.co/ovedrive/qwen-image-4bit)
Some models are converted without first being converted to diffusers models. Instead, BNB 4-bit quantization is performed directly on the original model. This will cause comfyui to fail to correctly perform mmdit conversion before loading these models. This is because they cannot recognize and correctly handle the newly added quantized vector format of BNB 4-bit.
Unsupported models:
- [flux.1-schnell-nf4](https://huggingface.co/gradjitta/flux.1-schnell-nf4)
- [flux1-schnell-bnb-nf4](https://huggingface.co/Keffisor21/flux1-schnell-bnb-nf4)
- [sd35-large-nf4](https://huggingface.co/sayakpaul/sd35-large-nf4)
+6
View File
@@ -0,0 +1,6 @@
# mengqin@gmail.com || Apache-2.0 (apache.org/licenses/LICENSE-2.0)
from .nodes import NODE_CLASS_MAPPINGS
NODE_DISPLAY_NAME_MAPPINGS = {k:v.TITLE for k,v in NODE_CLASS_MAPPINGS.items()}
__all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS']
+140
View File
@@ -0,0 +1,140 @@
# mengqin@gmail.com || Apache-2.0 (apache.org/licenses/LICENSE-2.0)
import logging
import os
import re
import safetensors
import torch
from comfy.cli_args import args
MMAP_TORCH_FILES = args.mmap_torch_files
DISABLE_MMAP = args.disable_mmap
ALWAYS_SAFE_LOAD = False
if hasattr(torch.serialization, "add_safe_globals"): # TODO: this was added in pytorch 2.4, the unsafe path should be removed once earlier versions are deprecated
ALWAYS_SAFE_LOAD = True
# Rewritten from load_troch_file() in utils.py to increase the ability to read shard files.
def safetensors_sd_loader(ckpt, safe_load=False, device=None, return_metadata=False):
if device is None:
device = torch.device("cpu")
metadata = None
def _load_single_safetensor_file(path, sd, metadata_holder):
try:
with safetensors.safe_open(path, framework="pt", device=device.type) as f:
for k in f.keys():
tensor = f.get_tensor(k)
if DISABLE_MMAP: # TODO: Not sure if this is the best way to bypass the mmap issues
tensor = tensor.to(device=device, copy=True)
if k in sd:
raise ValueError(f"Duplicate tensor key '{k}' found while loading shard {path}.")
sd[k] = tensor
if return_metadata:
m = f.metadata()
if metadata_holder[0] is None and m:
metadata_holder[0] = m
elif m and metadata_holder[0] is not None and m != metadata_holder[0]:
logging.warning("safetensors shard metadata mismatch: file %s metadata differs from previous shards.", path)
except Exception as e:
if len(e.args) > 0:
message = e.args[0]
if "HeaderTooLarge" in message:
raise ValueError("{}\n\nFile path: {}\n\nThe safetensors file is corrupt or invalid. Make sure this is actually a safetensors file and not a ckpt or pt or other filetype.".format(message, path))
if "MetadataIncompleteBuffer" in message:
raise ValueError("{}\n\nFile path: {}\n\nThe safetensors file is corrupt/incomplete. Check the file size and make sure you have copied/downloaded it correctly.".format(message, path))
raise
# If ckpt is a path to a directory try to find shards inside
try:
if isinstance(ckpt, str) and os.path.isdir(ckpt):
dirpath = ckpt
files = os.listdir(dirpath)
# pattern to detect HF-style shards: prefix<idx>-of-<total>.safetensors or .sft
shard_re = re.compile(r"^(.+)-(\d+)-of-(\d+)\.(safetensors|sft)$", flags=re.IGNORECASE)
groups = {}
for fname in files:
m = shard_re.match(fname)
if m:
prefix = m.group(1)
idx = int(m.group(2))
groups.setdefault(prefix, []).append((idx, fname))
selected_files = []
if groups:
best_prefix, members = max(groups.items(), key=lambda kv: len(kv[1]))
members_sorted = sorted(members, key=lambda t: t[0])
selected_files = [os.path.join(dirpath, fn) for (_, fn) in members_sorted]
else:
# fallback: load all .safetensors/.sft in the directory (if any)
safetensor_files = sorted([
os.path.join(dirpath, f) for f in files
if f.lower().endswith(".safetensors") or f.lower().endswith(".sft")
])
if safetensor_files:
selected_files = safetensor_files
if selected_files:
sd = {}
metadata_holder = [None]
for path in selected_files:
_load_single_safetensor_file(path, sd, metadata_holder)
metadata = metadata_holder[0]
return (sd, metadata) if return_metadata else sd
except Exception:
raise
# If ckpt is a path to a shard file (one shard provided), attempt to find sibling shards
if isinstance(ckpt, str) and (ckpt.lower().endswith(".safetensors") or ckpt.lower().endswith(".sft")) and os.path.isfile(ckpt):
# try to detect HF-style shard naming on this filename
shard_re = re.compile(r"^(.+)-(\d+)-of-(\d+)\.(safetensors|sft)$", flags=re.IGNORECASE)
base_name = os.path.basename(ckpt)
m = shard_re.match(base_name)
if m:
prefix = m.group(1)
dirpath = os.path.dirname(ckpt) or "."
sibling_pattern = re.compile(rf"^{re.escape(prefix)}-(\d+)-of-(\d+)\.(safetensors|sft)$", flags=re.IGNORECASE)
siblings = []
for fname in os.listdir(dirpath):
sm = sibling_pattern.match(fname)
if sm:
idx = int(sm.group(1))
siblings.append((idx, os.path.join(dirpath, fname)))
if siblings:
siblings_sorted = [p for (_, p) in sorted(siblings, key=lambda t: t[0])]
sd = {}
metadata_holder = [None]
for path in siblings_sorted:
_load_single_safetensor_file(path, sd, metadata_holder)
metadata = metadata_holder[0]
return (sd, metadata) if return_metadata else sd
if ckpt.lower().endswith(".safetensors") or ckpt.lower().endswith(".sft"):
try:
sd = {}
metadata_holder = [None]
_load_single_safetensor_file(ckpt, sd, metadata_holder)
metadata = metadata_holder[0]
return (sd, metadata) if return_metadata else sd
except Exception:
raise
torch_args = {}
if MMAP_TORCH_FILES:
torch_args["mmap"] = True
if safe_load or ALWAYS_SAFE_LOAD:
pl_sd = torch.load(ckpt, map_location=device, weights_only=True, **torch_args)
else:
logging.warning("WARNING: loading {} unsafely, upgrade your pytorch to 2.4 or newer to load this file safely.".format(ckpt))
pl_sd = torch.load(ckpt, map_location=device, pickle_module=comfy.checkpoint_pickle)
if "state_dict" in pl_sd:
sd = pl_sd["state_dict"]
else:
if len(pl_sd) == 1:
key = list(pl_sd.keys())[0]
sd = pl_sd[key]
if not isinstance(sd, dict):
sd = pl_sd
else:
sd = pl_sd
return (sd, metadata) if return_metadata else sd
+263
View File
@@ -0,0 +1,263 @@
# mengqin@gmail.com || Apache-2.0 (apache.org/licenses/LICENSE-2.0)
import logging
import os
import re
import uuid
import copy
import weakref
import torch
import comfy.sd
import comfy.model_patcher
import folder_paths
from .ops import LazyOps
from .loader import safetensors_sd_loader
class UnetBnbModelPatcher(comfy.model_patcher.ModelPatcher):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# module_key list of (strength_patch, patch_obj, strength_model, None, None)
self.bnb_lora_patches = {}
# optional backups for module-local temp data when partially_unload
self._bnb_lora_module_backups = {}
def add_patches(self, patches, strength_patch=1.0, strength_model=1.0):
added = []
for key in patches:
if not isinstance(key, str):
continue
module_key = key.rsplit('.', 1)[0]
try:
module = comfy.utils.get_attr(self.model, module_key)
is_bnb = hasattr(module, 'is_bnb_quantized') and module.is_bnb_quantized()
except Exception:
is_bnb = False
if is_bnb:
self.bnb_lora_patches.setdefault(module_key, []).append(
(strength_patch, patches[key], strength_model, None, None)
)
else:
current = self.patches.get(key, [])
current.append((strength_patch, patches[key], strength_model, None, None))
self.patches[key] = current
added.append(key)
self.patches_uuid = uuid.uuid4()
return added
def clone(self):
cloned = super().clone()
if not isinstance(cloned, UnetBnbModelPatcher):
new_cloned = UnetBnbModelPatcher(cloned.model, cloned.load_device, cloned.offload_device, cloned.size)
new_cloned.patches = cloned.patches
new_cloned.object_patches = cloned.object_patches
cloned = new_cloned
cloned.bnb_lora_patches = copy.deepcopy(self.bnb_lora_patches)
cloned._bnb_lora_module_backups = {}
return cloned
def pre_run(self, *args, **kwargs):
super().pre_run(*args, **kwargs)
for name, module in self.model.named_modules():
try:
if isinstance(module, LazyOps.Linear):
try:
module.patcher = weakref.proxy(self)
except Exception:
module.patcher = self
module.module_key_name = name
module.weight_key_name = f"{name}.weight"
except Exception:
logging.debug(f"pre_run: skip module {name} assignment due to exception", exc_info=True)
self.apply_bnb_patches()
def apply_bnb_patches(self):
for module_key, p_list in list(self.bnb_lora_patches.items()):
try:
module = comfy.utils.get_attr(self.model, module_key)
except Exception:
continue
if getattr(module, "_bnb_lora_attached", False):
continue
module._bnb_lora_attached = True
module._bnb_lora_patch_count = len(p_list)
def get_patches_for_module(self, module_key_name, *, is_bnb=False):
if is_bnb:
return self.bnb_lora_patches.get(module_key_name, None)
else:
return self.patches.get(f"{module_key_name}.weight", None)
def remove_bnb_patches(self):
for module_key in list(self.bnb_lora_patches.keys()):
try:
module = comfy.utils.get_attr(self.model, module_key)
except Exception:
continue
for attr in ("_bnb_lora_attached", "_bnb_lora_patch_count",):
if hasattr(module, attr):
try:
delattr(module, attr)
except Exception:
logging.debug(f"remove_bnb_patches: could not del {attr} on {module_key}", exc_info=True)
self._bnb_lora_module_backups.pop(module_key, None)
def clear_bnb_patches(self):
self.bnb_lora_patches.clear()
self._bnb_lora_module_backups.clear()
def unpatch_model(self, device_to=None, unpatch_weights=True):
super().unpatch_model(device_to=device_to, unpatch_weights=unpatch_weights)
self.remove_bnb_patches()
for name, module in self.model.named_modules():
if hasattr(module, "patcher"):
try:
p = getattr(module, "patcher")
delattr(module, "patcher")
except Exception:
pass
for attr in ("module_key_name", "weight_key_name"):
if hasattr(module, attr):
try:
delattr(module, attr)
except Exception:
pass
return
def partially_unload(self, device_to, memory_to_free=0):
memory_freed = super().partially_unload(device_to, memory_to_free=memory_to_free)
for name, module in self.model.named_modules():
if getattr(module, "_bnb_lora_attached", False):
module_key = getattr(module, "module_key_name", name)
if hasattr(module, "_bnb_lora_patch_count"):
self._bnb_lora_module_backups[module_key] = getattr(module, "_bnb_lora_patch_count", None)
for attr in ("_bnb_lora_attached", "_bnb_lora_patch_count",):
if hasattr(module, attr):
try:
delattr(module, attr)
except Exception:
pass
return memory_freed
def calculate_weight_with_patches(self, module_key_name, base_weight_fp32, is_bnb=False):
if is_bnb:
patches = self.bnb_lora_patches.get(module_key_name, None)
else:
patches = self.patches.get(f"{module_key_name}.weight", None)
if not patches:
return None
try:
base = base_weight_fp32.to(torch.float32)
weight_final_fp32 = comfy.lora.calculate_weight(patches, base, f"{module_key_name}.weight")
return weight_final_fp32.to(torch.float32)
except Exception:
logging.exception(f"calculate_weight_with_patches failed for {module_key_name}")
return None
def get_safetensors_model_list(folder_path_key):
shard_pattern = re.compile(r'.*-(\d{5})-of-(\d{5})\.safetensors$')
try:
initial_list = folder_paths.get_filename_list(folder_path_key)
except KeyError:
logging.error(f"Path type '{folder_path_key}' is not registered.")
return []
sharded_files_to_remove = set()
parent_dirs_to_add = set()
for item in initial_list:
is_dir = False
for basedir in folder_paths.get_folder_paths(folder_path_key):
if os.path.isdir(os.path.join(basedir, item)):
is_dir = True
break
if is_dir:
continue
filename = os.path.basename(item)
if shard_pattern.match(filename):
sharded_files_to_remove.add(item)
parent_dir = os.path.dirname(item)
if parent_dir and parent_dir != ".":
parent_dirs_to_add.add(parent_dir.replace(os.sep, '/'))
final_list = [item for item in initial_list if item not in sharded_files_to_remove]
final_list.extend(list(parent_dirs_to_add))
return sorted(list(set(final_list)))
def is_bnb_4bit(sd: dict) -> bool:
if not isinstance(sd, dict):
return False
for k in sd.keys():
if k.endswith(".quant_state.bitsandbytes__nf4") or k.endswith(".quant_state.bitsandbytes__fp4"):
return True
return False
class UnetBnbModelLoader:
FOLDER_PATH_KEY = "unet"
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"model_name": (get_safetensors_model_list(s.FOLDER_PATH_KEY),),
}
}
RETURN_TYPES = ("MODEL",)
FUNCTION = "load_model"
CATEGORY = "loaders"
TITLE = "Unet Bnb Model Loader"
def load_model(self, model_name):
model_path = folder_paths.get_full_path(self.FOLDER_PATH_KEY, model_name)
if model_path is None:
for basedir in folder_paths.get_folder_paths(self.FOLDER_PATH_KEY):
candidate_path = os.path.join(basedir, model_name)
if os.path.isdir(candidate_path):
model_path = candidate_path
break
if model_path is None:
raise FileNotFoundError(f"Model not found in the directory configured by '{self.FOLDER_PATH_KEY}' class: {model_name}")
state_dict = safetensors_sd_loader(model_path)
if is_bnb_4bit(state_dict):
model_patcher = comfy.sd.load_diffusion_model_state_dict(state_dict, {"custom_operations": LazyOps()})
custom_patcher = UnetBnbModelPatcher(model_patcher.model, model_patcher.load_device, model_patcher.offload_device, model_patcher.size)
else:
model_patcher = comfy.sd.load_diffusion_model_state_dict(state_dict)
custom_patcher = comfy.model_patcher.ModelPatcher(model_patcher.model, model_patcher.load_device, model_patcher.offload_device, model_patcher.size)
if model_patcher is None:
raise RuntimeError(f"Unable to detect or load UNet model: {model_path}")
return (custom_patcher,)
NODE_CLASS_MAPPINGS = {
"UnetBnbModelLoader": UnetBnbModelLoader,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"UnetBnbModelLoader": "Unet Bnb Model Loader",
}
+166
View File
@@ -0,0 +1,166 @@
# mengqin@gmail.com || Apache-2.0 (apache.org/licenses/LICENSE-2.0)
import torch
import comfy.ops
import comfy.model_management
import bitsandbytes as bnb
from bitsandbytes.nn.modules import Params4bit
import torch.nn.functional as F
import comfy
class LazyLayer(torch.nn.Module):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.is_bnb_4bit = False
self.is_fp8_scaled = False
def is_bnb_quantized(self):
return getattr(self, 'is_bnb_4bit', False)
def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict,
missing_keys, unexpected_keys, error_msgs):
weight_key = prefix + 'weight'
if weight_key in state_dict:
scale_weight_key = prefix +'scale_weight'
scale_input_key = prefix + 'scale_input'
# The dequantization type is determined layer by layer, supporting fp8_scaled and bnb 4bit.
# Other types of floating-point numbers are directly supported by the system.
if state_dict[weight_key].dtype in [torch.float8_e4m3fn, torch.float8_e5m2] and scale_weight_key in state_dict:
self.is_fp8_scaled = True
if scale_weight_key in state_dict:
self.register_buffer('scale_weight', state_dict[scale_weight_key])
if scale_input_key in state_dict:
self.register_buffer('scale_input', state_dict[scale_input_key])
else:
feature_key = f"{weight_key}.quant_state.bitsandbytes__nf4"
if feature_key not in state_dict:
feature_key = f"{weight_key}.quant_state.bitsandbytes__fp4"
if feature_key in state_dict:
self.is_bnb_4bit = True
device = comfy.model_management.get_torch_device()
bnb_state_dict = {k: v for k, v in state_dict.items() if k.startswith(weight_key)}
weight_data = bnb_state_dict.pop(weight_key)
quant_state_dict = {k[len(weight_key)+1:]: v for k, v in bnb_state_dict.items()}
bnb_param = Params4bit.from_prequantized(
data=weight_data, quantized_stats=quant_state_dict, device=device
)
self.weight = bnb_param
for k in bnb_state_dict.keys():
state_dict.pop(k)
if k in unexpected_keys: unexpected_keys.remove(k)
super()._load_from_state_dict(state_dict, prefix, local_metadata, strict,
missing_keys, unexpected_keys, error_msgs)
class LazyOps(comfy.ops.manual_cast):
class Linear(LazyLayer, comfy.ops.manual_cast.Linear):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.patcher = None
self.weight_key_name = None
def forward(self, x):
patcher = getattr(self, "patcher", None)
if patcher is not None:
try:
_ = patcher
except ReferenceError:
patcher = None
module_key = getattr(self, "module_key_name", None)
weight_key = f"{module_key}.weight" if module_key else None
patches_for_this_layer = None
if patcher is not None and module_key is not None:
try:
if self.is_bnb_quantized():
patches_for_this_layer = patcher.bnb_lora_patches.get(module_key, None)
else:
patches_for_this_layer = patcher.patches.get(weight_key, None)
except Exception:
patches_for_this_layer = None
if getattr(self, "is_bnb_quantized", lambda : False)():
if not patches_for_this_layer:
bias = self.bias.to(x.dtype) if self.bias is not None else None
return bnb.matmul_4bit(
x, self.weight.t(), bias=bias, quant_state=getattr(self.weight, "quant_state", None)
).to(x.dtype)
try:
base_w = self.weight.to(x.device)
base_dequant = bnb.functional.dequantize_4bit(base_w, base_w.quant_state).to(torch.float32)
except Exception:
base_dequant = self.weight.to(torch.float32).to(x.device)
weight_final_fp32 = None
if patcher is not None and module_key:
try:
weight_final_fp32 = patcher.calculate_weight_with_patches(module_key, base_dequant, is_bnb=True)
except Exception:
weight_final_fp32 = None
if weight_final_fp32 is None:
bias = self.bias.to(x.dtype) if self.bias is not None else None
return bnb.matmul_4bit(
x, self.weight.t(), bias=bias, quant_state=getattr(self.weight, "quant_state", None)
).to(x.dtype)
weight_final = comfy.float.stochastic_rounding(weight_final_fp32, x.dtype)
bias = self.bias.to(x.dtype) if self.bias is not None else None
return F.linear(x, weight_final.to(x.dtype), bias)
elif getattr(self, "is_fp8_scaled", False):
try:
base_weight_dequant = self.weight.to(torch.float32)
except Exception:
base_weight_dequant = self.weight.to(torch.float32)
scale_weight = getattr(self, 'scale_weight', None)
if scale_weight is None:
scale_weight = torch.tensor(1.0, device=base_weight_dequant.device, dtype=torch.float32)
try:
base_weight_dequant = base_weight_dequant * scale_weight.to(base_weight_dequant.device, torch.float32)
except Exception:
try:
base_weight_dequant = base_weight_dequant * scale_weight.to(base_weight_dequant.device)
except Exception:
pass
weight_final_fp32 = None
if patcher is not None and module_key:
try:
weight_final_fp32 = patcher.calculate_weight_with_patches(module_key, base_weight_dequant, is_bnb=False)
except Exception:
weight_final_fp32 = None
if weight_final_fp32 is None:
weight_final_fp32 = base_weight_dequant
weight_final = comfy.float.stochastic_rounding(weight_final_fp32, x.dtype)
bias = self.bias.to(x.dtype) if self.bias is not None else None
return F.linear(x, weight_final.to(x.dtype), bias)
else:
try:
return super().forward(x)
except Exception:
bias = self.bias.to(x.dtype) if self.bias is not None else None
return F.linear(x, self.weight.to(x.dtype), bias)
class Conv2d(comfy.ops.manual_cast.Conv2d): pass
class Embedding(comfy.ops.manual_cast.Embedding): pass
class LayerNorm(comfy.ops.manual_cast.LayerNorm): pass
class GroupNorm(comfy.ops.manual_cast.GroupNorm): pass
+14
View File
@@ -0,0 +1,14 @@
[project]
name = "comfyui-unetbnbmodelloader"
description = "Unet Bnb Model Loader"
version = "2.0.0" # 2.0.0 = GitHub main, 1.X.X = ComfyUI Registry
license = { file = "LICENSE" }
dependencies = ["bitsandbytes>=0.45.3"]
[project.urls]
Repository = "https://github.com/mengqin/ComfyUI-UnetBnbModelLoader"
[tool.comfy]
PublisherId = "mengqin"
DisplayName = "ComfyUI-UnetBnbModelLoader"
Icon = ""
+2
View File
@@ -0,0 +1,2 @@
# main
bitsandbytes>=0.45.3