Spaces:
Running
on
Zero
Running
on
Zero
Upload 750 files
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +9 -0
- .gitignore +26 -0
- alembic.ini +84 -0
- alembic_db/README.md +4 -0
- alembic_db/env.py +64 -0
- alembic_db/script.py.mako +28 -0
- api_server/__init__.py +0 -0
- api_server/routes/__init__.py +0 -0
- api_server/routes/internal/README.md +3 -0
- api_server/routes/internal/__init__.py +0 -0
- api_server/routes/internal/internal_routes.py +73 -0
- api_server/services/__init__.py +0 -0
- api_server/services/terminal_service.py +60 -0
- api_server/utils/file_operations.py +42 -0
- app.py +560 -0
- app/__init__.py +0 -0
- app/app_settings.py +65 -0
- app/custom_node_manager.py +145 -0
- app/database/db.py +112 -0
- app/database/models.py +14 -0
- app/frontend_management.py +326 -0
- app/logger.py +98 -0
- app/model_manager.py +184 -0
- app/user_manager.py +436 -0
- comfy/checkpoint_pickle.py +13 -0
- comfy/cldm/cldm.py +433 -0
- comfy/cldm/control_types.py +10 -0
- comfy/cldm/dit_embedder.py +120 -0
- comfy/cldm/mmdit.py +81 -0
- comfy/cli_args.py +235 -0
- comfy/clip_config_bigg.json +23 -0
- comfy/clip_model.py +244 -0
- comfy/clip_vision.py +148 -0
- comfy/clip_vision_config_g.json +18 -0
- comfy/clip_vision_config_h.json +18 -0
- comfy/clip_vision_config_vitl.json +18 -0
- comfy/clip_vision_config_vitl_336.json +18 -0
- comfy/clip_vision_config_vitl_336_llava.json +19 -0
- comfy/clip_vision_siglip_384.json +13 -0
- comfy/clip_vision_siglip_512.json +13 -0
- comfy/comfy_types/README.md +43 -0
- comfy/comfy_types/__init__.py +46 -0
- comfy/comfy_types/examples/example_nodes.py +28 -0
- comfy/comfy_types/examples/input_options.png +0 -0
- comfy/comfy_types/examples/input_types.png +0 -0
- comfy/comfy_types/examples/required_hint.png +0 -0
- comfy/comfy_types/node_typing.py +350 -0
- comfy/conds.py +130 -0
- comfy/controlnet.py +858 -0
- comfy/diffusers_convert.py +189 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,12 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
custom_nodes/ComfyUI_WanVideoWrapper/configs/T5_tokenizer/tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
custom_nodes/ComfyUI-KJNodes/docs/images/2024-04-03_20_49_29-ComfyUI.png filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
custom_nodes/ComfyUI-KJNodes/fonts/FreeMono.ttf filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
custom_nodes/ComfyUI-KJNodes/fonts/FreeMonoBoldOblique.otf filter=lfs diff=lfs merge=lfs -text
|
| 40 |
+
custom_nodes/ComfyUI-KJNodes/fonts/TTNorms-Black.otf filter=lfs diff=lfs merge=lfs -text
|
| 41 |
+
custom_nodes/ComfyUI-to-Python-Extension/images/comfyui_to_python_banner.png filter=lfs diff=lfs merge=lfs -text
|
| 42 |
+
custom_nodes/ComfyUI-to-Python-Extension/images/SDXL-UI-Example.PNG filter=lfs diff=lfs merge=lfs -text
|
| 43 |
+
input/009c.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 44 |
+
input/dasha.mp4 filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.py[cod]
|
| 3 |
+
/output/
|
| 4 |
+
/input/
|
| 5 |
+
!/input/example.png
|
| 6 |
+
/models/
|
| 7 |
+
/temp/
|
| 8 |
+
/custom_nodes/
|
| 9 |
+
!custom_nodes/example_node.py.example
|
| 10 |
+
extra_model_paths.yaml
|
| 11 |
+
/.vs
|
| 12 |
+
.vscode/
|
| 13 |
+
.idea/
|
| 14 |
+
venv/
|
| 15 |
+
.venv/
|
| 16 |
+
/web/extensions/*
|
| 17 |
+
!/web/extensions/logging.js.example
|
| 18 |
+
!/web/extensions/core/
|
| 19 |
+
/tests-ui/data/object_info.json
|
| 20 |
+
/user/
|
| 21 |
+
*.log
|
| 22 |
+
web_custom_versions/
|
| 23 |
+
.DS_Store
|
| 24 |
+
openapi.yaml
|
| 25 |
+
filtered-openapi.yaml
|
| 26 |
+
uv.lock
|
alembic.ini
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# A generic, single database configuration.
|
| 2 |
+
|
| 3 |
+
[alembic]
|
| 4 |
+
# path to migration scripts
|
| 5 |
+
# Use forward slashes (/) also on windows to provide an os agnostic path
|
| 6 |
+
script_location = alembic_db
|
| 7 |
+
|
| 8 |
+
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
|
| 9 |
+
# Uncomment the line below if you want the files to be prepended with date and time
|
| 10 |
+
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
|
| 11 |
+
# for all available tokens
|
| 12 |
+
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
|
| 13 |
+
|
| 14 |
+
# sys.path path, will be prepended to sys.path if present.
|
| 15 |
+
# defaults to the current working directory.
|
| 16 |
+
prepend_sys_path = .
|
| 17 |
+
|
| 18 |
+
# timezone to use when rendering the date within the migration file
|
| 19 |
+
# as well as the filename.
|
| 20 |
+
# If specified, requires the python>=3.9 or backports.zoneinfo library and tzdata library.
|
| 21 |
+
# Any required deps can installed by adding `alembic[tz]` to the pip requirements
|
| 22 |
+
# string value is passed to ZoneInfo()
|
| 23 |
+
# leave blank for localtime
|
| 24 |
+
# timezone =
|
| 25 |
+
|
| 26 |
+
# max length of characters to apply to the "slug" field
|
| 27 |
+
# truncate_slug_length = 40
|
| 28 |
+
|
| 29 |
+
# set to 'true' to run the environment during
|
| 30 |
+
# the 'revision' command, regardless of autogenerate
|
| 31 |
+
# revision_environment = false
|
| 32 |
+
|
| 33 |
+
# set to 'true' to allow .pyc and .pyo files without
|
| 34 |
+
# a source .py file to be detected as revisions in the
|
| 35 |
+
# versions/ directory
|
| 36 |
+
# sourceless = false
|
| 37 |
+
|
| 38 |
+
# version location specification; This defaults
|
| 39 |
+
# to alembic_db/versions. When using multiple version
|
| 40 |
+
# directories, initial revisions must be specified with --version-path.
|
| 41 |
+
# The path separator used here should be the separator specified by "version_path_separator" below.
|
| 42 |
+
# version_locations = %(here)s/bar:%(here)s/bat:alembic_db/versions
|
| 43 |
+
|
| 44 |
+
# version path separator; As mentioned above, this is the character used to split
|
| 45 |
+
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
|
| 46 |
+
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
|
| 47 |
+
# Valid values for version_path_separator are:
|
| 48 |
+
#
|
| 49 |
+
# version_path_separator = :
|
| 50 |
+
# version_path_separator = ;
|
| 51 |
+
# version_path_separator = space
|
| 52 |
+
# version_path_separator = newline
|
| 53 |
+
#
|
| 54 |
+
# Use os.pathsep. Default configuration used for new projects.
|
| 55 |
+
version_path_separator = os
|
| 56 |
+
|
| 57 |
+
# set to 'true' to search source files recursively
|
| 58 |
+
# in each "version_locations" directory
|
| 59 |
+
# new in Alembic version 1.10
|
| 60 |
+
# recursive_version_locations = false
|
| 61 |
+
|
| 62 |
+
# the output encoding used when revision files
|
| 63 |
+
# are written from script.py.mako
|
| 64 |
+
# output_encoding = utf-8
|
| 65 |
+
|
| 66 |
+
sqlalchemy.url = sqlite:///user/comfyui.db
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
[post_write_hooks]
|
| 70 |
+
# post_write_hooks defines scripts or Python functions that are run
|
| 71 |
+
# on newly generated revision scripts. See the documentation for further
|
| 72 |
+
# detail and examples
|
| 73 |
+
|
| 74 |
+
# format using "black" - use the console_scripts runner, against the "black" entrypoint
|
| 75 |
+
# hooks = black
|
| 76 |
+
# black.type = console_scripts
|
| 77 |
+
# black.entrypoint = black
|
| 78 |
+
# black.options = -l 79 REVISION_SCRIPT_FILENAME
|
| 79 |
+
|
| 80 |
+
# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
|
| 81 |
+
# hooks = ruff
|
| 82 |
+
# ruff.type = exec
|
| 83 |
+
# ruff.executable = %(here)s/.venv/bin/ruff
|
| 84 |
+
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
|
alembic_db/README.md
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
## Generate new revision
|
| 2 |
+
|
| 3 |
+
1. Update models in `/app/database/models.py`
|
| 4 |
+
2. Run `alembic revision --autogenerate -m "{your message}"`
|
alembic_db/env.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sqlalchemy import engine_from_config
|
| 2 |
+
from sqlalchemy import pool
|
| 3 |
+
|
| 4 |
+
from alembic import context
|
| 5 |
+
|
| 6 |
+
# this is the Alembic Config object, which provides
|
| 7 |
+
# access to the values within the .ini file in use.
|
| 8 |
+
config = context.config
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
from app.database.models import Base
|
| 12 |
+
target_metadata = Base.metadata
|
| 13 |
+
|
| 14 |
+
# other values from the config, defined by the needs of env.py,
|
| 15 |
+
# can be acquired:
|
| 16 |
+
# my_important_option = config.get_main_option("my_important_option")
|
| 17 |
+
# ... etc.
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def run_migrations_offline() -> None:
|
| 21 |
+
"""Run migrations in 'offline' mode.
|
| 22 |
+
This configures the context with just a URL
|
| 23 |
+
and not an Engine, though an Engine is acceptable
|
| 24 |
+
here as well. By skipping the Engine creation
|
| 25 |
+
we don't even need a DBAPI to be available.
|
| 26 |
+
Calls to context.execute() here emit the given string to the
|
| 27 |
+
script output.
|
| 28 |
+
"""
|
| 29 |
+
url = config.get_main_option("sqlalchemy.url")
|
| 30 |
+
context.configure(
|
| 31 |
+
url=url,
|
| 32 |
+
target_metadata=target_metadata,
|
| 33 |
+
literal_binds=True,
|
| 34 |
+
dialect_opts={"paramstyle": "named"},
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
with context.begin_transaction():
|
| 38 |
+
context.run_migrations()
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def run_migrations_online() -> None:
|
| 42 |
+
"""Run migrations in 'online' mode.
|
| 43 |
+
In this scenario we need to create an Engine
|
| 44 |
+
and associate a connection with the context.
|
| 45 |
+
"""
|
| 46 |
+
connectable = engine_from_config(
|
| 47 |
+
config.get_section(config.config_ini_section, {}),
|
| 48 |
+
prefix="sqlalchemy.",
|
| 49 |
+
poolclass=pool.NullPool,
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
with connectable.connect() as connection:
|
| 53 |
+
context.configure(
|
| 54 |
+
connection=connection, target_metadata=target_metadata
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
with context.begin_transaction():
|
| 58 |
+
context.run_migrations()
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
if context.is_offline_mode():
|
| 62 |
+
run_migrations_offline()
|
| 63 |
+
else:
|
| 64 |
+
run_migrations_online()
|
alembic_db/script.py.mako
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""${message}
|
| 2 |
+
|
| 3 |
+
Revision ID: ${up_revision}
|
| 4 |
+
Revises: ${down_revision | comma,n}
|
| 5 |
+
Create Date: ${create_date}
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
from typing import Sequence, Union
|
| 9 |
+
|
| 10 |
+
from alembic import op
|
| 11 |
+
import sqlalchemy as sa
|
| 12 |
+
${imports if imports else ""}
|
| 13 |
+
|
| 14 |
+
# revision identifiers, used by Alembic.
|
| 15 |
+
revision: str = ${repr(up_revision)}
|
| 16 |
+
down_revision: Union[str, None] = ${repr(down_revision)}
|
| 17 |
+
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
| 18 |
+
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def upgrade() -> None:
|
| 22 |
+
"""Upgrade schema."""
|
| 23 |
+
${upgrades if upgrades else "pass"}
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def downgrade() -> None:
|
| 27 |
+
"""Downgrade schema."""
|
| 28 |
+
${downgrades if downgrades else "pass"}
|
api_server/__init__.py
ADDED
|
File without changes
|
api_server/routes/__init__.py
ADDED
|
File without changes
|
api_server/routes/internal/README.md
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ComfyUI Internal Routes
|
| 2 |
+
|
| 3 |
+
All routes under the `/internal` path are designated for **internal use by ComfyUI only**. These routes are not intended for use by external applications may change at any time without notice.
|
api_server/routes/internal/__init__.py
ADDED
|
File without changes
|
api_server/routes/internal/internal_routes.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from aiohttp import web
|
| 2 |
+
from typing import Optional
|
| 3 |
+
from folder_paths import folder_names_and_paths, get_directory_by_type
|
| 4 |
+
from api_server.services.terminal_service import TerminalService
|
| 5 |
+
import app.logger
|
| 6 |
+
import os
|
| 7 |
+
|
| 8 |
+
class InternalRoutes:
|
| 9 |
+
'''
|
| 10 |
+
The top level web router for internal routes: /internal/*
|
| 11 |
+
The endpoints here should NOT be depended upon. It is for ComfyUI frontend use only.
|
| 12 |
+
Check README.md for more information.
|
| 13 |
+
'''
|
| 14 |
+
|
| 15 |
+
def __init__(self, prompt_server):
|
| 16 |
+
self.routes: web.RouteTableDef = web.RouteTableDef()
|
| 17 |
+
self._app: Optional[web.Application] = None
|
| 18 |
+
self.prompt_server = prompt_server
|
| 19 |
+
self.terminal_service = TerminalService(prompt_server)
|
| 20 |
+
|
| 21 |
+
def setup_routes(self):
|
| 22 |
+
@self.routes.get('/logs')
|
| 23 |
+
async def get_logs(request):
|
| 24 |
+
return web.json_response("".join([(l["t"] + " - " + l["m"]) for l in app.logger.get_logs()]))
|
| 25 |
+
|
| 26 |
+
@self.routes.get('/logs/raw')
|
| 27 |
+
async def get_raw_logs(request):
|
| 28 |
+
self.terminal_service.update_size()
|
| 29 |
+
return web.json_response({
|
| 30 |
+
"entries": list(app.logger.get_logs()),
|
| 31 |
+
"size": {"cols": self.terminal_service.cols, "rows": self.terminal_service.rows}
|
| 32 |
+
})
|
| 33 |
+
|
| 34 |
+
@self.routes.patch('/logs/subscribe')
|
| 35 |
+
async def subscribe_logs(request):
|
| 36 |
+
json_data = await request.json()
|
| 37 |
+
client_id = json_data["clientId"]
|
| 38 |
+
enabled = json_data["enabled"]
|
| 39 |
+
if enabled:
|
| 40 |
+
self.terminal_service.subscribe(client_id)
|
| 41 |
+
else:
|
| 42 |
+
self.terminal_service.unsubscribe(client_id)
|
| 43 |
+
|
| 44 |
+
return web.Response(status=200)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@self.routes.get('/folder_paths')
|
| 48 |
+
async def get_folder_paths(request):
|
| 49 |
+
response = {}
|
| 50 |
+
for key in folder_names_and_paths:
|
| 51 |
+
response[key] = folder_names_and_paths[key][0]
|
| 52 |
+
return web.json_response(response)
|
| 53 |
+
|
| 54 |
+
@self.routes.get('/files/{directory_type}')
|
| 55 |
+
async def get_files(request: web.Request) -> web.Response:
|
| 56 |
+
directory_type = request.match_info['directory_type']
|
| 57 |
+
if directory_type not in ("output", "input", "temp"):
|
| 58 |
+
return web.json_response({"error": "Invalid directory type"}, status=400)
|
| 59 |
+
|
| 60 |
+
directory = get_directory_by_type(directory_type)
|
| 61 |
+
sorted_files = sorted(
|
| 62 |
+
(entry for entry in os.scandir(directory) if entry.is_file()),
|
| 63 |
+
key=lambda entry: -entry.stat().st_mtime
|
| 64 |
+
)
|
| 65 |
+
return web.json_response([entry.name for entry in sorted_files], status=200)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def get_app(self):
|
| 69 |
+
if self._app is None:
|
| 70 |
+
self._app = web.Application()
|
| 71 |
+
self.setup_routes()
|
| 72 |
+
self._app.add_routes(self.routes)
|
| 73 |
+
return self._app
|
api_server/services/__init__.py
ADDED
|
File without changes
|
api_server/services/terminal_service.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from app.logger import on_flush
|
| 2 |
+
import os
|
| 3 |
+
import shutil
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class TerminalService:
|
| 7 |
+
def __init__(self, server):
|
| 8 |
+
self.server = server
|
| 9 |
+
self.cols = None
|
| 10 |
+
self.rows = None
|
| 11 |
+
self.subscriptions = set()
|
| 12 |
+
on_flush(self.send_messages)
|
| 13 |
+
|
| 14 |
+
def get_terminal_size(self):
|
| 15 |
+
try:
|
| 16 |
+
size = os.get_terminal_size()
|
| 17 |
+
return (size.columns, size.lines)
|
| 18 |
+
except OSError:
|
| 19 |
+
try:
|
| 20 |
+
size = shutil.get_terminal_size()
|
| 21 |
+
return (size.columns, size.lines)
|
| 22 |
+
except OSError:
|
| 23 |
+
return (80, 24) # fallback to 80x24
|
| 24 |
+
|
| 25 |
+
def update_size(self):
|
| 26 |
+
columns, lines = self.get_terminal_size()
|
| 27 |
+
changed = False
|
| 28 |
+
|
| 29 |
+
if columns != self.cols:
|
| 30 |
+
self.cols = columns
|
| 31 |
+
changed = True
|
| 32 |
+
|
| 33 |
+
if lines != self.rows:
|
| 34 |
+
self.rows = lines
|
| 35 |
+
changed = True
|
| 36 |
+
|
| 37 |
+
if changed:
|
| 38 |
+
return {"cols": self.cols, "rows": self.rows}
|
| 39 |
+
|
| 40 |
+
return None
|
| 41 |
+
|
| 42 |
+
def subscribe(self, client_id):
|
| 43 |
+
self.subscriptions.add(client_id)
|
| 44 |
+
|
| 45 |
+
def unsubscribe(self, client_id):
|
| 46 |
+
self.subscriptions.discard(client_id)
|
| 47 |
+
|
| 48 |
+
def send_messages(self, entries):
|
| 49 |
+
if not len(entries) or not len(self.subscriptions):
|
| 50 |
+
return
|
| 51 |
+
|
| 52 |
+
new_size = self.update_size()
|
| 53 |
+
|
| 54 |
+
for client_id in self.subscriptions.copy(): # prevent: Set changed size during iteration
|
| 55 |
+
if client_id not in self.server.sockets:
|
| 56 |
+
# Automatically unsub if the socket has disconnected
|
| 57 |
+
self.unsubscribe(client_id)
|
| 58 |
+
continue
|
| 59 |
+
|
| 60 |
+
self.server.send_sync("logs", {"entries": entries, "size": new_size}, client_id)
|
api_server/utils/file_operations.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from typing import List, Union, TypedDict, Literal
|
| 3 |
+
from typing_extensions import TypeGuard
|
| 4 |
+
class FileInfo(TypedDict):
|
| 5 |
+
name: str
|
| 6 |
+
path: str
|
| 7 |
+
type: Literal["file"]
|
| 8 |
+
size: int
|
| 9 |
+
|
| 10 |
+
class DirectoryInfo(TypedDict):
|
| 11 |
+
name: str
|
| 12 |
+
path: str
|
| 13 |
+
type: Literal["directory"]
|
| 14 |
+
|
| 15 |
+
FileSystemItem = Union[FileInfo, DirectoryInfo]
|
| 16 |
+
|
| 17 |
+
def is_file_info(item: FileSystemItem) -> TypeGuard[FileInfo]:
|
| 18 |
+
return item["type"] == "file"
|
| 19 |
+
|
| 20 |
+
class FileSystemOperations:
|
| 21 |
+
@staticmethod
|
| 22 |
+
def walk_directory(directory: str) -> List[FileSystemItem]:
|
| 23 |
+
file_list: List[FileSystemItem] = []
|
| 24 |
+
for root, dirs, files in os.walk(directory):
|
| 25 |
+
for name in files:
|
| 26 |
+
file_path = os.path.join(root, name)
|
| 27 |
+
relative_path = os.path.relpath(file_path, directory)
|
| 28 |
+
file_list.append({
|
| 29 |
+
"name": name,
|
| 30 |
+
"path": relative_path,
|
| 31 |
+
"type": "file",
|
| 32 |
+
"size": os.path.getsize(file_path)
|
| 33 |
+
})
|
| 34 |
+
for name in dirs:
|
| 35 |
+
dir_path = os.path.join(root, name)
|
| 36 |
+
relative_path = os.path.relpath(dir_path, directory)
|
| 37 |
+
file_list.append({
|
| 38 |
+
"name": name,
|
| 39 |
+
"path": relative_path,
|
| 40 |
+
"type": "directory"
|
| 41 |
+
})
|
| 42 |
+
return file_list
|
app.py
ADDED
|
@@ -0,0 +1,560 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import cv2
|
| 3 |
+
import numpy as np
|
| 4 |
+
import random
|
| 5 |
+
import sys
|
| 6 |
+
import subprocess
|
| 7 |
+
from typing import Sequence, Mapping, Any, Union
|
| 8 |
+
import torch
|
| 9 |
+
from tqdm import tqdm
|
| 10 |
+
import argparse
|
| 11 |
+
import json
|
| 12 |
+
import logging
|
| 13 |
+
|
| 14 |
+
import shutil
|
| 15 |
+
import gradio as gr
|
| 16 |
+
import spaces
|
| 17 |
+
from huggingface_hub import snapshot_download
|
| 18 |
+
import time
|
| 19 |
+
import traceback
|
| 20 |
+
|
| 21 |
+
from utils import get_path_after_pexel
|
| 22 |
+
|
| 23 |
+
LOCAL_GRADIO_TMP = os.path.abspath("./gradio_tmp")
|
| 24 |
+
os.makedirs(LOCAL_GRADIO_TMP, exist_ok=True)
|
| 25 |
+
os.environ["GRADIO_TEMP_DIR"] = LOCAL_GRADIO_TMP
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
HF_REPOS = {
|
| 29 |
+
"QingyanBai/Ditto_models": ["models_comfy/ditto_global_comfy.safetensors"],
|
| 30 |
+
"Kijai/WanVideo_comfy": [
|
| 31 |
+
"Wan2_1-T2V-14B_fp8_e4m3fn.safetensors",
|
| 32 |
+
"Wan21_CausVid_14B_T2V_lora_rank32_v2.safetensors",
|
| 33 |
+
"Wan2_1_VAE_bf16.safetensors",
|
| 34 |
+
"umt5-xxl-enc-bf16.safetensors",
|
| 35 |
+
],
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
MODELS_ROOT = os.path.abspath(os.path.join(os.getcwd(), "models"))
|
| 39 |
+
PATHS = {
|
| 40 |
+
"diffusion_model": os.path.join(MODELS_ROOT, "diffusion_models"),
|
| 41 |
+
"vae_wan": os.path.join(MODELS_ROOT, "vae", "wan"),
|
| 42 |
+
"loras": os.path.join(MODELS_ROOT, "loras"),
|
| 43 |
+
"text_encoders": os.path.join(MODELS_ROOT, "text_encoders"),
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
REQUIRED_FILES = [
|
| 47 |
+
("Wan2_1-T2V-14B_fp8_e4m3fn.safetensors", "diffusion_model"),
|
| 48 |
+
("ditto_global_comfy.safetensors", "diffusion_model"),
|
| 49 |
+
("Wan21_CausVid_14B_T2V_lora_rank32_v2.safetensors", "loras"),
|
| 50 |
+
("Wan2_1_VAE_bf16.safetensors", "vae_wan"),
|
| 51 |
+
("umt5-xxl-enc-bf16.safetensors", "text_encoders"),
|
| 52 |
+
]
|
| 53 |
+
|
| 54 |
+
def ensure_dir(path: str) -> None:
|
| 55 |
+
os.makedirs(path, exist_ok=True)
|
| 56 |
+
|
| 57 |
+
def ensure_models() -> None:
|
| 58 |
+
for filename, key in REQUIRED_FILES:
|
| 59 |
+
target_dir = PATHS[key]
|
| 60 |
+
ensure_dir(target_dir)
|
| 61 |
+
target_path = os.path.join(target_dir, filename)
|
| 62 |
+
ready_flag = os.path.join(target_dir, f"{filename}.READY")
|
| 63 |
+
|
| 64 |
+
if os.path.exists(target_path) and os.path.getsize(target_path) > 0:
|
| 65 |
+
open(ready_flag, "a").close()
|
| 66 |
+
continue
|
| 67 |
+
|
| 68 |
+
repo_id = None
|
| 69 |
+
repo_file_path = None
|
| 70 |
+
for repo, files in HF_REPOS.items():
|
| 71 |
+
for file_path in files:
|
| 72 |
+
if filename in file_path:
|
| 73 |
+
repo_id = repo
|
| 74 |
+
repo_file_path = file_path
|
| 75 |
+
break
|
| 76 |
+
if repo_id:
|
| 77 |
+
break
|
| 78 |
+
|
| 79 |
+
if repo_id is None:
|
| 80 |
+
raise RuntimeError(f"Could not find repository for file: {filename}")
|
| 81 |
+
|
| 82 |
+
print(f"Downloading {filename} from {repo_id} to {target_dir} ...")
|
| 83 |
+
|
| 84 |
+
snapshot_download(
|
| 85 |
+
repo_id=repo_id,
|
| 86 |
+
local_dir=target_dir,
|
| 87 |
+
local_dir_use_symlinks=False,
|
| 88 |
+
allow_patterns=[repo_file_path],
|
| 89 |
+
token=os.getenv("HF_TOKEN", None),
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
if not os.path.exists(target_path):
|
| 93 |
+
found = []
|
| 94 |
+
for root, _, files in os.walk(target_dir):
|
| 95 |
+
for f in files:
|
| 96 |
+
if f == filename:
|
| 97 |
+
found.append(os.path.join(root, f))
|
| 98 |
+
if found:
|
| 99 |
+
src = found[0]
|
| 100 |
+
if src != target_path:
|
| 101 |
+
shutil.copy2(src, target_path)
|
| 102 |
+
|
| 103 |
+
if not os.path.exists(target_path):
|
| 104 |
+
raise RuntimeError(f"Failed to download required file: {filename}")
|
| 105 |
+
|
| 106 |
+
open(ready_flag, "w").close()
|
| 107 |
+
print(f"Downloaded and ready: {target_path}")
|
| 108 |
+
ensure_models()
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def ensure_t5_tokenizer() -> None:
|
| 112 |
+
"""
|
| 113 |
+
Ensure the local T5 tokenizer folder exists and contains valid files.
|
| 114 |
+
If missing or corrupted, download from 'google/umt5-xxl' and save locally
|
| 115 |
+
to the exact path expected by the WanVideo wrapper nodes.
|
| 116 |
+
"""
|
| 117 |
+
try:
|
| 118 |
+
script_directory = os.path.dirname(os.path.abspath(__file__))
|
| 119 |
+
tokenizer_dir = os.path.join(
|
| 120 |
+
script_directory,
|
| 121 |
+
"custom_nodes",
|
| 122 |
+
"ComfyUI_WanVideoWrapper",
|
| 123 |
+
"configs",
|
| 124 |
+
"T5_tokenizer",
|
| 125 |
+
)
|
| 126 |
+
os.makedirs(tokenizer_dir, exist_ok=True)
|
| 127 |
+
|
| 128 |
+
required_files = [
|
| 129 |
+
"tokenizer.json",
|
| 130 |
+
"tokenizer_config.json",
|
| 131 |
+
"spiece.model",
|
| 132 |
+
"special_tokens_map.json",
|
| 133 |
+
]
|
| 134 |
+
|
| 135 |
+
def is_valid(path: str) -> bool:
|
| 136 |
+
return os.path.exists(path) and os.path.getsize(path) > 0
|
| 137 |
+
|
| 138 |
+
all_ok = all(is_valid(os.path.join(tokenizer_dir, f)) for f in required_files)
|
| 139 |
+
if all_ok:
|
| 140 |
+
print(f"T5 tokenizer ready at: {tokenizer_dir}")
|
| 141 |
+
return
|
| 142 |
+
|
| 143 |
+
print(f"Preparing T5 tokenizer at: {tokenizer_dir} ...")
|
| 144 |
+
from transformers import AutoTokenizer
|
| 145 |
+
|
| 146 |
+
tok = AutoTokenizer.from_pretrained(
|
| 147 |
+
"google/umt5-xxl",
|
| 148 |
+
use_fast=True,
|
| 149 |
+
trust_remote_code=False,
|
| 150 |
+
)
|
| 151 |
+
tok.save_pretrained(tokenizer_dir)
|
| 152 |
+
|
| 153 |
+
# Re-check
|
| 154 |
+
all_ok = all(is_valid(os.path.join(tokenizer_dir, f)) for f in required_files)
|
| 155 |
+
if not all_ok:
|
| 156 |
+
raise RuntimeError("Tokenizer files not fully prepared after save_pretrained")
|
| 157 |
+
print("T5 tokenizer prepared successfully.")
|
| 158 |
+
except Exception as e:
|
| 159 |
+
print(f"Failed to prepare T5 tokenizer: {e}\n{traceback.format_exc()}")
|
| 160 |
+
raise
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
ensure_t5_tokenizer()
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def setup_global_logging_filter():
|
| 167 |
+
class MemoryLogFilter(logging.Filter):
|
| 168 |
+
def filter(self, record):
|
| 169 |
+
msg = record.getMessage()
|
| 170 |
+
keywords = [
|
| 171 |
+
"Allocated memory:",
|
| 172 |
+
"Max allocated memory:",
|
| 173 |
+
"Max reserved memory:",
|
| 174 |
+
"memory=",
|
| 175 |
+
"max_memory=",
|
| 176 |
+
"max_reserved=",
|
| 177 |
+
"Block swap memory summary",
|
| 178 |
+
"Transformer blocks on",
|
| 179 |
+
"Total memory used by",
|
| 180 |
+
"Non-blocking memory transfer"
|
| 181 |
+
]
|
| 182 |
+
return not any(kw in msg for kw in keywords)
|
| 183 |
+
|
| 184 |
+
logging.basicConfig(
|
| 185 |
+
level=logging.INFO,
|
| 186 |
+
format='%(asctime)s - %(levelname)s - %(message)s',
|
| 187 |
+
force=True
|
| 188 |
+
)
|
| 189 |
+
logging.getLogger().handlers[0].addFilter(MemoryLogFilter())
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
setup_global_logging_filter()
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def tensor_to_video(video_tensor, output_path, fps=20, crf=20):
|
| 196 |
+
frames = video_tensor.detach().cpu().numpy()
|
| 197 |
+
if frames.dtype != np.uint8:
|
| 198 |
+
if frames.max() <= 1.0:
|
| 199 |
+
frames = (frames * 255).astype(np.uint8)
|
| 200 |
+
else:
|
| 201 |
+
frames = frames.astype(np.uint8)
|
| 202 |
+
num_frames, height, width, _ = frames.shape
|
| 203 |
+
command = [
|
| 204 |
+
'ffmpeg',
|
| 205 |
+
'-y',
|
| 206 |
+
'-f', 'rawvideo',
|
| 207 |
+
'-vcodec', 'rawvideo',
|
| 208 |
+
'-pix_fmt', 'rgb24',
|
| 209 |
+
'-s', f'{width}x{height}',
|
| 210 |
+
'-r', str(fps),
|
| 211 |
+
'-i', '-',
|
| 212 |
+
'-c:v', 'libx264',
|
| 213 |
+
'-pix_fmt', 'yuv420p',
|
| 214 |
+
'-crf', str(crf),
|
| 215 |
+
'-preset', 'medium',
|
| 216 |
+
'-r', str(fps),
|
| 217 |
+
'-an',
|
| 218 |
+
output_path
|
| 219 |
+
]
|
| 220 |
+
|
| 221 |
+
with subprocess.Popen(command, stdin=subprocess.PIPE, stderr=subprocess.PIPE) as proc:
|
| 222 |
+
for frame in frames:
|
| 223 |
+
proc.stdin.write(frame.tobytes())
|
| 224 |
+
proc.stdin.close()
|
| 225 |
+
if proc.stderr is not None:
|
| 226 |
+
proc.stderr.read()
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def get_value_at_index(obj: Union[Sequence, Mapping], index: int) -> Any:
|
| 230 |
+
try:
|
| 231 |
+
return obj[index]
|
| 232 |
+
except KeyError:
|
| 233 |
+
return obj["result"][index]
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def find_path(name: str, path: str = None) -> str:
|
| 237 |
+
if path is None:
|
| 238 |
+
path = os.getcwd()
|
| 239 |
+
if name in os.listdir(path):
|
| 240 |
+
path_name = os.path.join(path, name)
|
| 241 |
+
print(f"{name} found: {path_name}")
|
| 242 |
+
return path_name
|
| 243 |
+
parent_directory = os.path.dirname(path)
|
| 244 |
+
if parent_directory == path:
|
| 245 |
+
return None
|
| 246 |
+
return find_path(name, parent_directory)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def add_comfyui_directory_to_sys_path() -> None:
|
| 250 |
+
comfyui_path = find_path("ComfyUI")
|
| 251 |
+
if comfyui_path is not None and os.path.isdir(comfyui_path):
|
| 252 |
+
if comfyui_path not in sys.path:
|
| 253 |
+
sys.path.append(comfyui_path)
|
| 254 |
+
print(f"'{comfyui_path}' added to sys.path")
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def add_extra_model_paths() -> None:
|
| 258 |
+
try:
|
| 259 |
+
from main import load_extra_path_config
|
| 260 |
+
except ImportError:
|
| 261 |
+
print(
|
| 262 |
+
"Could not import load_extra_path_config from main.py. Looking in utils.extra_config instead."
|
| 263 |
+
)
|
| 264 |
+
from utils.extra_config import load_extra_path_config
|
| 265 |
+
|
| 266 |
+
extra_model_paths = find_path("extra_model_paths.yaml")
|
| 267 |
+
|
| 268 |
+
if extra_model_paths is not None:
|
| 269 |
+
load_extra_path_config(extra_model_paths)
|
| 270 |
+
else:
|
| 271 |
+
print("Could not find the extra_model_paths config file.")
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
add_comfyui_directory_to_sys_path()
|
| 275 |
+
add_extra_model_paths()
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def import_custom_nodes() -> None:
|
| 279 |
+
import asyncio
|
| 280 |
+
import execution
|
| 281 |
+
from nodes import init_extra_nodes
|
| 282 |
+
import server
|
| 283 |
+
|
| 284 |
+
if getattr(import_custom_nodes, "_initialized", False):
|
| 285 |
+
return
|
| 286 |
+
|
| 287 |
+
loop = asyncio.new_event_loop()
|
| 288 |
+
asyncio.set_event_loop(loop)
|
| 289 |
+
server_instance = server.PromptServer(loop)
|
| 290 |
+
execution.PromptQueue(server_instance)
|
| 291 |
+
init_extra_nodes()
|
| 292 |
+
import_custom_nodes._initialized = True
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
from nodes import NODE_CLASS_MAPPINGS
|
| 296 |
+
|
| 297 |
+
print(f"Loading custom nodes and models...")
|
| 298 |
+
import_custom_nodes()
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
@spaces.GPU()
|
| 302 |
+
def run_pipeline(vpath, prompt, width, height, fps, frame_count, outdir):
|
| 303 |
+
try:
|
| 304 |
+
import gc
|
| 305 |
+
# Clean memory before starting
|
| 306 |
+
gc.collect()
|
| 307 |
+
if torch.cuda.is_available():
|
| 308 |
+
torch.cuda.empty_cache()
|
| 309 |
+
|
| 310 |
+
os.makedirs(outdir, exist_ok=True)
|
| 311 |
+
|
| 312 |
+
with torch.inference_mode():
|
| 313 |
+
from custom_nodes.ComfyUI_WanVideoWrapper import nodes as wan_nodes
|
| 314 |
+
vhs_loadvideo = NODE_CLASS_MAPPINGS["VHS_LoadVideo"]()
|
| 315 |
+
|
| 316 |
+
# Set model and settings.
|
| 317 |
+
wanvideovacemodelselect = wan_nodes.WanVideoVACEModelSelect()
|
| 318 |
+
wanvideovacemodelselect_89 = wanvideovacemodelselect.getvacepath(
|
| 319 |
+
vace_model="ditto_global_comfy.safetensors"
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
wanvideoslg = wan_nodes.WanVideoSLG()
|
| 323 |
+
wanvideoslg_113 = wanvideoslg.process(
|
| 324 |
+
blocks="2",
|
| 325 |
+
start_percent=0.20000000000000004,
|
| 326 |
+
end_percent=0.7000000000000002,
|
| 327 |
+
)
|
| 328 |
+
wanvideovaeloader = wan_nodes.WanVideoVAELoader()
|
| 329 |
+
wanvideovaeloader_133 = wanvideovaeloader.loadmodel(
|
| 330 |
+
model_name="wan/Wan2_1_VAE_bf16.safetensors", precision="bf16"
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
loadwanvideot5textencoder = wan_nodes.LoadWanVideoT5TextEncoder()
|
| 334 |
+
loadwanvideot5textencoder_134 = loadwanvideot5textencoder.loadmodel(
|
| 335 |
+
model_name="umt5-xxl-enc-bf16.safetensors",
|
| 336 |
+
precision="bf16",
|
| 337 |
+
load_device="offload_device",
|
| 338 |
+
quantization="disabled",
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
wanvideoblockswap = wan_nodes.WanVideoBlockSwap()
|
| 342 |
+
wanvideoblockswap_137 = wanvideoblockswap.setargs(
|
| 343 |
+
blocks_to_swap=30,
|
| 344 |
+
offload_img_emb=False,
|
| 345 |
+
offload_txt_emb=False,
|
| 346 |
+
use_non_blocking=True,
|
| 347 |
+
vace_blocks_to_swap=0,
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
wanvideoloraselect = wan_nodes.WanVideoLoraSelect()
|
| 351 |
+
wanvideoloraselect_380 = wanvideoloraselect.getlorapath(
|
| 352 |
+
lora="Wan21_CausVid_14B_T2V_lora_rank32_v2.safetensors",
|
| 353 |
+
strength=1.0,
|
| 354 |
+
low_mem_load=False,
|
| 355 |
+
)
|
| 356 |
+
|
| 357 |
+
wanvideomodelloader = wan_nodes.WanVideoModelLoader()
|
| 358 |
+
imageresizekjv2 = NODE_CLASS_MAPPINGS["ImageResizeKJv2"]()
|
| 359 |
+
wanvideovaceencode = wan_nodes.WanVideoVACEEncode()
|
| 360 |
+
wanvideotextencode = wan_nodes.WanVideoTextEncode()
|
| 361 |
+
wanvideosampler = wan_nodes.WanVideoSampler()
|
| 362 |
+
wanvideodecode = wan_nodes.WanVideoDecode()
|
| 363 |
+
wanvideomodelloader_142 = wanvideomodelloader.loadmodel(
|
| 364 |
+
model="Wan2_1-T2V-14B_fp8_e4m3fn.safetensors",
|
| 365 |
+
base_precision="fp16",
|
| 366 |
+
quantization="disabled",
|
| 367 |
+
load_device="offload_device",
|
| 368 |
+
attention_mode="sdpa",
|
| 369 |
+
block_swap_args=get_value_at_index(wanvideoblockswap_137, 0),
|
| 370 |
+
lora=get_value_at_index(wanvideoloraselect_380, 0),
|
| 371 |
+
vace_model=get_value_at_index(wanvideovacemodelselect_89, 0),
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
fname = os.path.basename(vpath)
|
| 375 |
+
fname_clean = os.path.splitext(fname)[0]
|
| 376 |
+
|
| 377 |
+
vhs_loadvideo_70 = vhs_loadvideo.load_video(
|
| 378 |
+
video=vpath,
|
| 379 |
+
force_rate=24,
|
| 380 |
+
custom_width=width,
|
| 381 |
+
custom_height=height,
|
| 382 |
+
frame_load_cap=frame_count,
|
| 383 |
+
skip_first_frames=1,
|
| 384 |
+
select_every_nth=1,
|
| 385 |
+
format="AnimateDiff",
|
| 386 |
+
unique_id=16696422174153060213,
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
imageresizekjv2_205 = imageresizekjv2.resize(
|
| 390 |
+
width=width,
|
| 391 |
+
height=height,
|
| 392 |
+
upscale_method="area",
|
| 393 |
+
keep_proportion="resize",
|
| 394 |
+
pad_color="0, 0, 0",
|
| 395 |
+
crop_position="center",
|
| 396 |
+
divisible_by=8,
|
| 397 |
+
device="cpu",
|
| 398 |
+
image=get_value_at_index(vhs_loadvideo_70, 0),
|
| 399 |
+
)
|
| 400 |
+
wanvideovaceencode_29 = wanvideovaceencode.process(
|
| 401 |
+
width=width,
|
| 402 |
+
height=height,
|
| 403 |
+
num_frames=frame_count,
|
| 404 |
+
strength=0.9750000000000002,
|
| 405 |
+
vace_start_percent=0,
|
| 406 |
+
vace_end_percent=1,
|
| 407 |
+
tiled_vae=False,
|
| 408 |
+
vae=get_value_at_index(wanvideovaeloader_133, 0),
|
| 409 |
+
input_frames=get_value_at_index(imageresizekjv2_205, 0),
|
| 410 |
+
)
|
| 411 |
+
|
| 412 |
+
wanvideotextencode_148 = wanvideotextencode.process(
|
| 413 |
+
positive_prompt=prompt,
|
| 414 |
+
negative_prompt="flickering artifact, jpg artifacts, compression, distortion, morphing, low-res, fake, oversaturated, overexposed, over bright, strange behavior, distorted limbs, unnatural motion, unrealistic anatomy, glitch, extra limbs,",
|
| 415 |
+
force_offload=True,
|
| 416 |
+
t5=get_value_at_index(loadwanvideot5textencoder_134, 0),
|
| 417 |
+
model_to_offload=get_value_at_index(wanvideomodelloader_142, 0),
|
| 418 |
+
)
|
| 419 |
+
|
| 420 |
+
# Clean memory before sampling (most memory-intensive step)
|
| 421 |
+
gc.collect()
|
| 422 |
+
if torch.cuda.is_available():
|
| 423 |
+
torch.cuda.empty_cache()
|
| 424 |
+
|
| 425 |
+
wanvideosampler_2 = wanvideosampler.process(
|
| 426 |
+
steps=4,
|
| 427 |
+
cfg=1.2000000000000002,
|
| 428 |
+
shift=2.0000000000000004,
|
| 429 |
+
seed=random.randint(1, 2 ** 64),
|
| 430 |
+
force_offload=True,
|
| 431 |
+
scheduler="unipc",
|
| 432 |
+
riflex_freq_index=0,
|
| 433 |
+
denoise_strength=1,
|
| 434 |
+
batched_cfg=False,
|
| 435 |
+
rope_function="comfy",
|
| 436 |
+
model=get_value_at_index(wanvideomodelloader_142, 0),
|
| 437 |
+
image_embeds=get_value_at_index(wanvideovaceencode_29, 0),
|
| 438 |
+
text_embeds=get_value_at_index(wanvideotextencode_148, 0),
|
| 439 |
+
slg_args=get_value_at_index(wanvideoslg_113, 0),
|
| 440 |
+
)
|
| 441 |
+
res = wanvideodecode.decode(
|
| 442 |
+
enable_vae_tiling=False,
|
| 443 |
+
tile_x=272,
|
| 444 |
+
tile_y=272,
|
| 445 |
+
tile_stride_x=144,
|
| 446 |
+
tile_stride_y=128,
|
| 447 |
+
vae=get_value_at_index(wanvideovaeloader_133, 0),
|
| 448 |
+
samples=get_value_at_index(wanvideosampler_2, 0),
|
| 449 |
+
)
|
| 450 |
+
save_path = os.path.join(outdir, f'{fname_clean}_edit.mp4')
|
| 451 |
+
tensor_to_video(res[0], save_path, fps=fps)
|
| 452 |
+
|
| 453 |
+
# Clean up memory after generation
|
| 454 |
+
del res
|
| 455 |
+
gc.collect()
|
| 456 |
+
if torch.cuda.is_available():
|
| 457 |
+
torch.cuda.empty_cache()
|
| 458 |
+
|
| 459 |
+
print(f"Done. Saved to: {save_path}")
|
| 460 |
+
return save_path
|
| 461 |
+
except Exception as e:
|
| 462 |
+
err = f"Error: {e}\n{traceback.format_exc()}"
|
| 463 |
+
print(err)
|
| 464 |
+
# Clean memory on error too
|
| 465 |
+
gc.collect()
|
| 466 |
+
if torch.cuda.is_available():
|
| 467 |
+
torch.cuda.empty_cache()
|
| 468 |
+
raise
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
@spaces.GPU()
|
| 472 |
+
def gradio_infer(vfile, prompt, width, height, fps, frame_count, progress=gr.Progress(track_tqdm=True)):
|
| 473 |
+
if vfile is None:
|
| 474 |
+
return None, "Please upload the video!", "\n".join(logs)
|
| 475 |
+
|
| 476 |
+
vpath = vfile if isinstance(vfile, str) else vfile.name
|
| 477 |
+
if not os.path.exists(vpath) and hasattr(vfile, "save"):
|
| 478 |
+
os.makedirs("uploads", exist_ok=True)
|
| 479 |
+
vpath = os.path.join("uploads", os.path.basename(vfile.name))
|
| 480 |
+
vfile.save(vpath)
|
| 481 |
+
|
| 482 |
+
outdir = "results"
|
| 483 |
+
os.makedirs(outdir, exist_ok=True)
|
| 484 |
+
|
| 485 |
+
save_path = run_pipeline(
|
| 486 |
+
vpath=vpath,
|
| 487 |
+
prompt=prompt,
|
| 488 |
+
width=int(width),
|
| 489 |
+
height=int(height),
|
| 490 |
+
fps=int(fps),
|
| 491 |
+
frame_count=int(frame_count),
|
| 492 |
+
outdir=outdir,
|
| 493 |
+
)
|
| 494 |
+
return save_path
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
def build_interface():
|
| 498 |
+
with gr.Blocks(title="Ditto") as demo:
|
| 499 |
+
gr.Markdown(
|
| 500 |
+
"""# Ditto: Scaling Instruction-Based Video Editing with a High-Quality Synthetic Dataset
|
| 501 |
+
|
| 502 |
+
<div style="font-size: 1.3rem; line-height: 1.6; margin-bottom: 1rem;">
|
| 503 |
+
<a href="https://arxiv.org/abs/2510.15742" target="_blank">📄 Paper</a>
|
| 504 |
+
|
|
| 505 |
+
<a href="https://ezioby.github.io/Ditto_page/" target="_blank">🌐 Project Page</a>
|
| 506 |
+
|
|
| 507 |
+
<a href="https://github.com/EzioBy/Ditto/" target="_blank"> 💻 Github Code </a>
|
| 508 |
+
|
|
| 509 |
+
<a href="https://huggingface.co/QingyanBai/Ditto_models/tree/main" target="_blank">📦 Model Weights</a>
|
| 510 |
+
|
|
| 511 |
+
<a href="https://huggingface.co/datasets/QingyanBai/Ditto-1M" target="_blank">📊 Dataset</a>
|
| 512 |
+
</div>
|
| 513 |
+
|
| 514 |
+
<b>Note1:</b> The backend of this demo is comfy, please note that due to the use of quantized and distilled models, there may be some quality degradation.
|
| 515 |
+
<b>Note2:</b> Considering the limited memory, please try test cases with lower resolution and frame count, otherwise it may cause out of memory error.
|
| 516 |
+
If you like this project, please consider <a href="https://github.com/EzioBy/Ditto/" target="_blank">starring the repo</a> to motivate us. Thank you!
|
| 517 |
+
"""
|
| 518 |
+
)
|
| 519 |
+
|
| 520 |
+
with gr.Column():
|
| 521 |
+
with gr.Row():
|
| 522 |
+
vfile = gr.Video(label="Input Video", value=os.path.join("input", "dasha.mp4"),
|
| 523 |
+
sources="upload", interactive=True)
|
| 524 |
+
out_video = gr.Video(label="Result")
|
| 525 |
+
prompt = gr.Textbox(label="Editing Instruction", value="Make it in the style of Japanese anime")
|
| 526 |
+
with gr.Row():
|
| 527 |
+
width = gr.Number(label="Width", value=576, precision=0)
|
| 528 |
+
height = gr.Number(label="Height", value=324, precision=0)
|
| 529 |
+
fps = gr.Number(label="FPS", value=20, precision=0)
|
| 530 |
+
frame_count = gr.Number(label="Frame Count", value=49, precision=0)
|
| 531 |
+
run_btn = gr.Button("Run", variant="primary")
|
| 532 |
+
|
| 533 |
+
run_btn.click(
|
| 534 |
+
fn=gradio_infer,
|
| 535 |
+
inputs=[vfile, prompt, width, height, fps, frame_count],
|
| 536 |
+
outputs=[out_video]
|
| 537 |
+
)
|
| 538 |
+
examples = [
|
| 539 |
+
[
|
| 540 |
+
os.path.join("input", "dasha.mp4"),
|
| 541 |
+
"Add some fire and flame to the background",
|
| 542 |
+
576, 324, 20, 49
|
| 543 |
+
],
|
| 544 |
+
[
|
| 545 |
+
os.path.join("input", "dasha.mp4"),
|
| 546 |
+
"Make it in the style of pencil sketch",
|
| 547 |
+
576, 324, 20, 49
|
| 548 |
+
],
|
| 549 |
+
]
|
| 550 |
+
gr.Examples(
|
| 551 |
+
examples=examples,
|
| 552 |
+
inputs=[vfile, prompt, width, height, fps, frame_count],
|
| 553 |
+
label="Examples"
|
| 554 |
+
)
|
| 555 |
+
return demo
|
| 556 |
+
|
| 557 |
+
|
| 558 |
+
if __name__ == "__main__":
|
| 559 |
+
demo = build_interface()
|
| 560 |
+
demo.launch()
|
app/__init__.py
ADDED
|
File without changes
|
app/app_settings.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
from aiohttp import web
|
| 4 |
+
import logging
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class AppSettings():
|
| 8 |
+
def __init__(self, user_manager):
|
| 9 |
+
self.user_manager = user_manager
|
| 10 |
+
|
| 11 |
+
def get_settings(self, request):
|
| 12 |
+
try:
|
| 13 |
+
file = self.user_manager.get_request_user_filepath(
|
| 14 |
+
request,
|
| 15 |
+
"comfy.settings.json"
|
| 16 |
+
)
|
| 17 |
+
except KeyError as e:
|
| 18 |
+
logging.error("User settings not found.")
|
| 19 |
+
raise web.HTTPUnauthorized() from e
|
| 20 |
+
if os.path.isfile(file):
|
| 21 |
+
try:
|
| 22 |
+
with open(file) as f:
|
| 23 |
+
return json.load(f)
|
| 24 |
+
except:
|
| 25 |
+
logging.error(f"The user settings file is corrupted: {file}")
|
| 26 |
+
return {}
|
| 27 |
+
else:
|
| 28 |
+
return {}
|
| 29 |
+
|
| 30 |
+
def save_settings(self, request, settings):
|
| 31 |
+
file = self.user_manager.get_request_user_filepath(
|
| 32 |
+
request, "comfy.settings.json")
|
| 33 |
+
with open(file, "w") as f:
|
| 34 |
+
f.write(json.dumps(settings, indent=4))
|
| 35 |
+
|
| 36 |
+
def add_routes(self, routes):
|
| 37 |
+
@routes.get("/settings")
|
| 38 |
+
async def get_settings(request):
|
| 39 |
+
return web.json_response(self.get_settings(request))
|
| 40 |
+
|
| 41 |
+
@routes.get("/settings/{id}")
|
| 42 |
+
async def get_setting(request):
|
| 43 |
+
value = None
|
| 44 |
+
settings = self.get_settings(request)
|
| 45 |
+
setting_id = request.match_info.get("id", None)
|
| 46 |
+
if setting_id and setting_id in settings:
|
| 47 |
+
value = settings[setting_id]
|
| 48 |
+
return web.json_response(value)
|
| 49 |
+
|
| 50 |
+
@routes.post("/settings")
|
| 51 |
+
async def post_settings(request):
|
| 52 |
+
settings = self.get_settings(request)
|
| 53 |
+
new_settings = await request.json()
|
| 54 |
+
self.save_settings(request, {**settings, **new_settings})
|
| 55 |
+
return web.Response(status=200)
|
| 56 |
+
|
| 57 |
+
@routes.post("/settings/{id}")
|
| 58 |
+
async def post_setting(request):
|
| 59 |
+
setting_id = request.match_info.get("id", None)
|
| 60 |
+
if not setting_id:
|
| 61 |
+
return web.Response(status=400)
|
| 62 |
+
settings = self.get_settings(request)
|
| 63 |
+
settings[setting_id] = await request.json()
|
| 64 |
+
self.save_settings(request, settings)
|
| 65 |
+
return web.Response(status=200)
|
app/custom_node_manager.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import folder_paths
|
| 5 |
+
import glob
|
| 6 |
+
from aiohttp import web
|
| 7 |
+
import json
|
| 8 |
+
import logging
|
| 9 |
+
from functools import lru_cache
|
| 10 |
+
|
| 11 |
+
from utils.json_util import merge_json_recursive
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
# Extra locale files to load into main.json
|
| 15 |
+
EXTRA_LOCALE_FILES = [
|
| 16 |
+
"nodeDefs.json",
|
| 17 |
+
"commands.json",
|
| 18 |
+
"settings.json",
|
| 19 |
+
]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def safe_load_json_file(file_path: str) -> dict:
|
| 23 |
+
if not os.path.exists(file_path):
|
| 24 |
+
return {}
|
| 25 |
+
|
| 26 |
+
try:
|
| 27 |
+
with open(file_path, "r", encoding="utf-8") as f:
|
| 28 |
+
return json.load(f)
|
| 29 |
+
except json.JSONDecodeError:
|
| 30 |
+
logging.error(f"Error loading {file_path}")
|
| 31 |
+
return {}
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class CustomNodeManager:
|
| 35 |
+
@lru_cache(maxsize=1)
|
| 36 |
+
def build_translations(self):
|
| 37 |
+
"""Load all custom nodes translations during initialization. Translations are
|
| 38 |
+
expected to be loaded from `locales/` folder.
|
| 39 |
+
|
| 40 |
+
The folder structure is expected to be the following:
|
| 41 |
+
- custom_nodes/
|
| 42 |
+
- custom_node_1/
|
| 43 |
+
- locales/
|
| 44 |
+
- en/
|
| 45 |
+
- main.json
|
| 46 |
+
- commands.json
|
| 47 |
+
- settings.json
|
| 48 |
+
|
| 49 |
+
returned translations are expected to be in the following format:
|
| 50 |
+
{
|
| 51 |
+
"en": {
|
| 52 |
+
"nodeDefs": {...},
|
| 53 |
+
"commands": {...},
|
| 54 |
+
"settings": {...},
|
| 55 |
+
...{other main.json keys}
|
| 56 |
+
}
|
| 57 |
+
}
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
translations = {}
|
| 61 |
+
|
| 62 |
+
for folder in folder_paths.get_folder_paths("custom_nodes"):
|
| 63 |
+
# Sort glob results for deterministic ordering
|
| 64 |
+
for custom_node_dir in sorted(glob.glob(os.path.join(folder, "*/"))):
|
| 65 |
+
locales_dir = os.path.join(custom_node_dir, "locales")
|
| 66 |
+
if not os.path.exists(locales_dir):
|
| 67 |
+
continue
|
| 68 |
+
|
| 69 |
+
for lang_dir in glob.glob(os.path.join(locales_dir, "*/")):
|
| 70 |
+
lang_code = os.path.basename(os.path.dirname(lang_dir))
|
| 71 |
+
|
| 72 |
+
if lang_code not in translations:
|
| 73 |
+
translations[lang_code] = {}
|
| 74 |
+
|
| 75 |
+
# Load main.json
|
| 76 |
+
main_file = os.path.join(lang_dir, "main.json")
|
| 77 |
+
node_translations = safe_load_json_file(main_file)
|
| 78 |
+
|
| 79 |
+
# Load extra locale files
|
| 80 |
+
for extra_file in EXTRA_LOCALE_FILES:
|
| 81 |
+
extra_file_path = os.path.join(lang_dir, extra_file)
|
| 82 |
+
key = extra_file.split(".")[0]
|
| 83 |
+
json_data = safe_load_json_file(extra_file_path)
|
| 84 |
+
if json_data:
|
| 85 |
+
node_translations[key] = json_data
|
| 86 |
+
|
| 87 |
+
if node_translations:
|
| 88 |
+
translations[lang_code] = merge_json_recursive(
|
| 89 |
+
translations[lang_code], node_translations
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
return translations
|
| 93 |
+
|
| 94 |
+
def add_routes(self, routes, webapp, loadedModules):
|
| 95 |
+
|
| 96 |
+
example_workflow_folder_names = ["example_workflows", "example", "examples", "workflow", "workflows"]
|
| 97 |
+
|
| 98 |
+
@routes.get("/workflow_templates")
|
| 99 |
+
async def get_workflow_templates(request):
|
| 100 |
+
"""Returns a web response that contains the map of custom_nodes names and their associated workflow templates. The ones without templates are omitted."""
|
| 101 |
+
|
| 102 |
+
files = []
|
| 103 |
+
|
| 104 |
+
for folder in folder_paths.get_folder_paths("custom_nodes"):
|
| 105 |
+
for folder_name in example_workflow_folder_names:
|
| 106 |
+
pattern = os.path.join(folder, f"*/{folder_name}/*.json")
|
| 107 |
+
matched_files = glob.glob(pattern)
|
| 108 |
+
files.extend(matched_files)
|
| 109 |
+
|
| 110 |
+
workflow_templates_dict = (
|
| 111 |
+
{}
|
| 112 |
+
) # custom_nodes folder name -> example workflow names
|
| 113 |
+
for file in files:
|
| 114 |
+
custom_nodes_name = os.path.basename(
|
| 115 |
+
os.path.dirname(os.path.dirname(file))
|
| 116 |
+
)
|
| 117 |
+
workflow_name = os.path.splitext(os.path.basename(file))[0]
|
| 118 |
+
workflow_templates_dict.setdefault(custom_nodes_name, []).append(
|
| 119 |
+
workflow_name
|
| 120 |
+
)
|
| 121 |
+
return web.json_response(workflow_templates_dict)
|
| 122 |
+
|
| 123 |
+
# Serve workflow templates from custom nodes.
|
| 124 |
+
for module_name, module_dir in loadedModules:
|
| 125 |
+
for folder_name in example_workflow_folder_names:
|
| 126 |
+
workflows_dir = os.path.join(module_dir, folder_name)
|
| 127 |
+
|
| 128 |
+
if os.path.exists(workflows_dir):
|
| 129 |
+
if folder_name != "example_workflows":
|
| 130 |
+
logging.debug(
|
| 131 |
+
"Found example workflow folder '%s' for custom node '%s', consider renaming it to 'example_workflows'",
|
| 132 |
+
folder_name, module_name)
|
| 133 |
+
|
| 134 |
+
webapp.add_routes(
|
| 135 |
+
[
|
| 136 |
+
web.static(
|
| 137 |
+
"/api/workflow_templates/" + module_name, workflows_dir
|
| 138 |
+
)
|
| 139 |
+
]
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
@routes.get("/i18n")
|
| 143 |
+
async def get_i18n(request):
|
| 144 |
+
"""Returns translations from all custom nodes' locales folders."""
|
| 145 |
+
return web.json_response(self.build_translations())
|
app/database/db.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import os
|
| 3 |
+
import shutil
|
| 4 |
+
from app.logger import log_startup_warning
|
| 5 |
+
from utils.install_util import get_missing_requirements_message
|
| 6 |
+
from comfy.cli_args import args
|
| 7 |
+
|
| 8 |
+
_DB_AVAILABLE = False
|
| 9 |
+
Session = None
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
from alembic import command
|
| 14 |
+
from alembic.config import Config
|
| 15 |
+
from alembic.runtime.migration import MigrationContext
|
| 16 |
+
from alembic.script import ScriptDirectory
|
| 17 |
+
from sqlalchemy import create_engine
|
| 18 |
+
from sqlalchemy.orm import sessionmaker
|
| 19 |
+
|
| 20 |
+
_DB_AVAILABLE = True
|
| 21 |
+
except ImportError as e:
|
| 22 |
+
log_startup_warning(
|
| 23 |
+
f"""
|
| 24 |
+
------------------------------------------------------------------------
|
| 25 |
+
Error importing dependencies: {e}
|
| 26 |
+
{get_missing_requirements_message()}
|
| 27 |
+
This error is happening because ComfyUI now uses a local sqlite database.
|
| 28 |
+
------------------------------------------------------------------------
|
| 29 |
+
""".strip()
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def dependencies_available():
|
| 34 |
+
"""
|
| 35 |
+
Temporary function to check if the dependencies are available
|
| 36 |
+
"""
|
| 37 |
+
return _DB_AVAILABLE
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def can_create_session():
|
| 41 |
+
"""
|
| 42 |
+
Temporary function to check if the database is available to create a session
|
| 43 |
+
During initial release there may be environmental issues (or missing dependencies) that prevent the database from being created
|
| 44 |
+
"""
|
| 45 |
+
return dependencies_available() and Session is not None
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def get_alembic_config():
|
| 49 |
+
root_path = os.path.join(os.path.dirname(__file__), "../..")
|
| 50 |
+
config_path = os.path.abspath(os.path.join(root_path, "alembic.ini"))
|
| 51 |
+
scripts_path = os.path.abspath(os.path.join(root_path, "alembic_db"))
|
| 52 |
+
|
| 53 |
+
config = Config(config_path)
|
| 54 |
+
config.set_main_option("script_location", scripts_path)
|
| 55 |
+
config.set_main_option("sqlalchemy.url", args.database_url)
|
| 56 |
+
|
| 57 |
+
return config
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def get_db_path():
|
| 61 |
+
url = args.database_url
|
| 62 |
+
if url.startswith("sqlite:///"):
|
| 63 |
+
return url.split("///")[1]
|
| 64 |
+
else:
|
| 65 |
+
raise ValueError(f"Unsupported database URL '{url}'.")
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def init_db():
|
| 69 |
+
db_url = args.database_url
|
| 70 |
+
logging.debug(f"Database URL: {db_url}")
|
| 71 |
+
db_path = get_db_path()
|
| 72 |
+
db_exists = os.path.exists(db_path)
|
| 73 |
+
|
| 74 |
+
config = get_alembic_config()
|
| 75 |
+
|
| 76 |
+
# Check if we need to upgrade
|
| 77 |
+
engine = create_engine(db_url)
|
| 78 |
+
conn = engine.connect()
|
| 79 |
+
|
| 80 |
+
context = MigrationContext.configure(conn)
|
| 81 |
+
current_rev = context.get_current_revision()
|
| 82 |
+
|
| 83 |
+
script = ScriptDirectory.from_config(config)
|
| 84 |
+
target_rev = script.get_current_head()
|
| 85 |
+
|
| 86 |
+
if target_rev is None:
|
| 87 |
+
logging.warning("No target revision found.")
|
| 88 |
+
elif current_rev != target_rev:
|
| 89 |
+
# Backup the database pre upgrade
|
| 90 |
+
backup_path = db_path + ".bkp"
|
| 91 |
+
if db_exists:
|
| 92 |
+
shutil.copy(db_path, backup_path)
|
| 93 |
+
else:
|
| 94 |
+
backup_path = None
|
| 95 |
+
|
| 96 |
+
try:
|
| 97 |
+
command.upgrade(config, target_rev)
|
| 98 |
+
logging.info(f"Database upgraded from {current_rev} to {target_rev}")
|
| 99 |
+
except Exception as e:
|
| 100 |
+
if backup_path:
|
| 101 |
+
# Restore the database from backup if upgrade fails
|
| 102 |
+
shutil.copy(backup_path, db_path)
|
| 103 |
+
os.remove(backup_path)
|
| 104 |
+
logging.exception("Error upgrading database: ")
|
| 105 |
+
raise e
|
| 106 |
+
|
| 107 |
+
global Session
|
| 108 |
+
Session = sessionmaker(bind=engine)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def create_session():
|
| 112 |
+
return Session()
|
app/database/models.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sqlalchemy.orm import declarative_base
|
| 2 |
+
|
| 3 |
+
Base = declarative_base()
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def to_dict(obj):
|
| 7 |
+
fields = obj.__table__.columns.keys()
|
| 8 |
+
return {
|
| 9 |
+
field: (val.to_dict() if hasattr(val, "to_dict") else val)
|
| 10 |
+
for field in fields
|
| 11 |
+
if (val := getattr(obj, field))
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
# TODO: Define models here
|
app/frontend_management.py
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import argparse
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
import re
|
| 6 |
+
import sys
|
| 7 |
+
import tempfile
|
| 8 |
+
import zipfile
|
| 9 |
+
import importlib
|
| 10 |
+
from dataclasses import dataclass
|
| 11 |
+
from functools import cached_property
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from typing import TypedDict, Optional
|
| 14 |
+
from importlib.metadata import version
|
| 15 |
+
|
| 16 |
+
import requests
|
| 17 |
+
from typing_extensions import NotRequired
|
| 18 |
+
|
| 19 |
+
from utils.install_util import get_missing_requirements_message, requirements_path
|
| 20 |
+
|
| 21 |
+
from comfy.cli_args import DEFAULT_VERSION_STRING
|
| 22 |
+
import app.logger
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def frontend_install_warning_message():
|
| 26 |
+
return f"""
|
| 27 |
+
{get_missing_requirements_message()}
|
| 28 |
+
|
| 29 |
+
This error is happening because the ComfyUI frontend is no longer shipped as part of the main repo but as a pip package instead.
|
| 30 |
+
""".strip()
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def check_frontend_version():
|
| 34 |
+
"""Check if the frontend version is up to date."""
|
| 35 |
+
|
| 36 |
+
def parse_version(version: str) -> tuple[int, int, int]:
|
| 37 |
+
return tuple(map(int, version.split(".")))
|
| 38 |
+
|
| 39 |
+
try:
|
| 40 |
+
frontend_version_str = version("comfyui-frontend-package")
|
| 41 |
+
frontend_version = parse_version(frontend_version_str)
|
| 42 |
+
with open(requirements_path, "r", encoding="utf-8") as f:
|
| 43 |
+
required_frontend = parse_version(f.readline().split("=")[-1])
|
| 44 |
+
if frontend_version < required_frontend:
|
| 45 |
+
app.logger.log_startup_warning(
|
| 46 |
+
f"""
|
| 47 |
+
________________________________________________________________________
|
| 48 |
+
WARNING WARNING WARNING WARNING WARNING
|
| 49 |
+
|
| 50 |
+
Installed frontend version {".".join(map(str, frontend_version))} is lower than the recommended version {".".join(map(str, required_frontend))}.
|
| 51 |
+
|
| 52 |
+
{frontend_install_warning_message()}
|
| 53 |
+
________________________________________________________________________
|
| 54 |
+
""".strip()
|
| 55 |
+
)
|
| 56 |
+
else:
|
| 57 |
+
logging.info("ComfyUI frontend version: {}".format(frontend_version_str))
|
| 58 |
+
except Exception as e:
|
| 59 |
+
logging.error(f"Failed to check frontend version: {e}")
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
REQUEST_TIMEOUT = 10 # seconds
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class Asset(TypedDict):
|
| 66 |
+
url: str
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class Release(TypedDict):
|
| 70 |
+
id: int
|
| 71 |
+
tag_name: str
|
| 72 |
+
name: str
|
| 73 |
+
prerelease: bool
|
| 74 |
+
created_at: str
|
| 75 |
+
published_at: str
|
| 76 |
+
body: str
|
| 77 |
+
assets: NotRequired[list[Asset]]
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
@dataclass
|
| 81 |
+
class FrontEndProvider:
|
| 82 |
+
owner: str
|
| 83 |
+
repo: str
|
| 84 |
+
|
| 85 |
+
@property
|
| 86 |
+
def folder_name(self) -> str:
|
| 87 |
+
return f"{self.owner}_{self.repo}"
|
| 88 |
+
|
| 89 |
+
@property
|
| 90 |
+
def release_url(self) -> str:
|
| 91 |
+
return f"https://api.github.com/repos/{self.owner}/{self.repo}/releases"
|
| 92 |
+
|
| 93 |
+
@cached_property
|
| 94 |
+
def all_releases(self) -> list[Release]:
|
| 95 |
+
releases = []
|
| 96 |
+
api_url = self.release_url
|
| 97 |
+
while api_url:
|
| 98 |
+
response = requests.get(api_url, timeout=REQUEST_TIMEOUT)
|
| 99 |
+
response.raise_for_status() # Raises an HTTPError if the response was an error
|
| 100 |
+
releases.extend(response.json())
|
| 101 |
+
# GitHub uses the Link header to provide pagination links. Check if it exists and update api_url accordingly.
|
| 102 |
+
if "next" in response.links:
|
| 103 |
+
api_url = response.links["next"]["url"]
|
| 104 |
+
else:
|
| 105 |
+
api_url = None
|
| 106 |
+
return releases
|
| 107 |
+
|
| 108 |
+
@cached_property
|
| 109 |
+
def latest_release(self) -> Release:
|
| 110 |
+
latest_release_url = f"{self.release_url}/latest"
|
| 111 |
+
response = requests.get(latest_release_url, timeout=REQUEST_TIMEOUT)
|
| 112 |
+
response.raise_for_status() # Raises an HTTPError if the response was an error
|
| 113 |
+
return response.json()
|
| 114 |
+
|
| 115 |
+
@cached_property
|
| 116 |
+
def latest_prerelease(self) -> Release:
|
| 117 |
+
"""Get the latest pre-release version - even if it's older than the latest release"""
|
| 118 |
+
release = [release for release in self.all_releases if release["prerelease"]]
|
| 119 |
+
|
| 120 |
+
if not release:
|
| 121 |
+
raise ValueError("No pre-releases found")
|
| 122 |
+
|
| 123 |
+
# GitHub returns releases in reverse chronological order, so first is latest
|
| 124 |
+
return release[0]
|
| 125 |
+
|
| 126 |
+
def get_release(self, version: str) -> Release:
|
| 127 |
+
if version == "latest":
|
| 128 |
+
return self.latest_release
|
| 129 |
+
elif version == "prerelease":
|
| 130 |
+
return self.latest_prerelease
|
| 131 |
+
else:
|
| 132 |
+
for release in self.all_releases:
|
| 133 |
+
if release["tag_name"] in [version, f"v{version}"]:
|
| 134 |
+
return release
|
| 135 |
+
raise ValueError(f"Version {version} not found in releases")
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def download_release_asset_zip(release: Release, destination_path: str) -> None:
|
| 139 |
+
"""Download dist.zip from github release."""
|
| 140 |
+
asset_url = None
|
| 141 |
+
for asset in release.get("assets", []):
|
| 142 |
+
if asset["name"] == "dist.zip":
|
| 143 |
+
asset_url = asset["url"]
|
| 144 |
+
break
|
| 145 |
+
|
| 146 |
+
if not asset_url:
|
| 147 |
+
raise ValueError("dist.zip not found in the release assets")
|
| 148 |
+
|
| 149 |
+
# Use a temporary file to download the zip content
|
| 150 |
+
with tempfile.TemporaryFile() as tmp_file:
|
| 151 |
+
headers = {"Accept": "application/octet-stream"}
|
| 152 |
+
response = requests.get(
|
| 153 |
+
asset_url, headers=headers, allow_redirects=True, timeout=REQUEST_TIMEOUT
|
| 154 |
+
)
|
| 155 |
+
response.raise_for_status() # Ensure we got a successful response
|
| 156 |
+
|
| 157 |
+
# Write the content to the temporary file
|
| 158 |
+
tmp_file.write(response.content)
|
| 159 |
+
|
| 160 |
+
# Go back to the beginning of the temporary file
|
| 161 |
+
tmp_file.seek(0)
|
| 162 |
+
|
| 163 |
+
# Extract the zip file content to the destination path
|
| 164 |
+
with zipfile.ZipFile(tmp_file, "r") as zip_ref:
|
| 165 |
+
zip_ref.extractall(destination_path)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
class FrontendManager:
|
| 169 |
+
CUSTOM_FRONTENDS_ROOT = str(Path(__file__).parents[1] / "web_custom_versions")
|
| 170 |
+
|
| 171 |
+
@classmethod
|
| 172 |
+
def default_frontend_path(cls) -> str:
|
| 173 |
+
try:
|
| 174 |
+
import comfyui_frontend_package
|
| 175 |
+
|
| 176 |
+
return str(importlib.resources.files(comfyui_frontend_package) / "static")
|
| 177 |
+
except ImportError:
|
| 178 |
+
logging.error(
|
| 179 |
+
f"""
|
| 180 |
+
********** ERROR ***********
|
| 181 |
+
|
| 182 |
+
comfyui-frontend-package is not installed.
|
| 183 |
+
|
| 184 |
+
{frontend_install_warning_message()}
|
| 185 |
+
|
| 186 |
+
********** ERROR ***********
|
| 187 |
+
""".strip()
|
| 188 |
+
)
|
| 189 |
+
sys.exit(-1)
|
| 190 |
+
|
| 191 |
+
@classmethod
|
| 192 |
+
def templates_path(cls) -> str:
|
| 193 |
+
try:
|
| 194 |
+
import comfyui_workflow_templates
|
| 195 |
+
|
| 196 |
+
return str(
|
| 197 |
+
importlib.resources.files(comfyui_workflow_templates) / "templates"
|
| 198 |
+
)
|
| 199 |
+
except ImportError:
|
| 200 |
+
logging.error(
|
| 201 |
+
f"""
|
| 202 |
+
********** ERROR ***********
|
| 203 |
+
|
| 204 |
+
comfyui-workflow-templates is not installed.
|
| 205 |
+
|
| 206 |
+
{frontend_install_warning_message()}
|
| 207 |
+
|
| 208 |
+
********** ERROR ***********
|
| 209 |
+
""".strip()
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
@classmethod
|
| 213 |
+
def embedded_docs_path(cls) -> str:
|
| 214 |
+
"""Get the path to embedded documentation"""
|
| 215 |
+
try:
|
| 216 |
+
import comfyui_embedded_docs
|
| 217 |
+
|
| 218 |
+
return str(
|
| 219 |
+
importlib.resources.files(comfyui_embedded_docs) / "docs"
|
| 220 |
+
)
|
| 221 |
+
except ImportError:
|
| 222 |
+
logging.info("comfyui-embedded-docs package not found")
|
| 223 |
+
return None
|
| 224 |
+
|
| 225 |
+
@classmethod
|
| 226 |
+
def parse_version_string(cls, value: str) -> tuple[str, str, str]:
|
| 227 |
+
"""
|
| 228 |
+
Args:
|
| 229 |
+
value (str): The version string to parse.
|
| 230 |
+
|
| 231 |
+
Returns:
|
| 232 |
+
tuple[str, str]: A tuple containing provider name and version.
|
| 233 |
+
|
| 234 |
+
Raises:
|
| 235 |
+
argparse.ArgumentTypeError: If the version string is invalid.
|
| 236 |
+
"""
|
| 237 |
+
VERSION_PATTERN = r"^([a-zA-Z0-9][a-zA-Z0-9-]{0,38})/([a-zA-Z0-9_.-]+)@(v?\d+\.\d+\.\d+[-._a-zA-Z0-9]*|latest|prerelease)$"
|
| 238 |
+
match_result = re.match(VERSION_PATTERN, value)
|
| 239 |
+
if match_result is None:
|
| 240 |
+
raise argparse.ArgumentTypeError(f"Invalid version string: {value}")
|
| 241 |
+
|
| 242 |
+
return match_result.group(1), match_result.group(2), match_result.group(3)
|
| 243 |
+
|
| 244 |
+
@classmethod
|
| 245 |
+
def init_frontend_unsafe(
|
| 246 |
+
cls, version_string: str, provider: Optional[FrontEndProvider] = None
|
| 247 |
+
) -> str:
|
| 248 |
+
"""
|
| 249 |
+
Initializes the frontend for the specified version.
|
| 250 |
+
|
| 251 |
+
Args:
|
| 252 |
+
version_string (str): The version string.
|
| 253 |
+
provider (FrontEndProvider, optional): The provider to use. Defaults to None.
|
| 254 |
+
|
| 255 |
+
Returns:
|
| 256 |
+
str: The path to the initialized frontend.
|
| 257 |
+
|
| 258 |
+
Raises:
|
| 259 |
+
Exception: If there is an error during the initialization process.
|
| 260 |
+
main error source might be request timeout or invalid URL.
|
| 261 |
+
"""
|
| 262 |
+
if version_string == DEFAULT_VERSION_STRING:
|
| 263 |
+
check_frontend_version()
|
| 264 |
+
return cls.default_frontend_path()
|
| 265 |
+
|
| 266 |
+
repo_owner, repo_name, version = cls.parse_version_string(version_string)
|
| 267 |
+
|
| 268 |
+
if version.startswith("v"):
|
| 269 |
+
expected_path = str(
|
| 270 |
+
Path(cls.CUSTOM_FRONTENDS_ROOT)
|
| 271 |
+
/ f"{repo_owner}_{repo_name}"
|
| 272 |
+
/ version.lstrip("v")
|
| 273 |
+
)
|
| 274 |
+
if os.path.exists(expected_path):
|
| 275 |
+
logging.info(
|
| 276 |
+
f"Using existing copy of specific frontend version tag: {repo_owner}/{repo_name}@{version}"
|
| 277 |
+
)
|
| 278 |
+
return expected_path
|
| 279 |
+
|
| 280 |
+
logging.info(
|
| 281 |
+
f"Initializing frontend: {repo_owner}/{repo_name}@{version}, requesting version details from GitHub..."
|
| 282 |
+
)
|
| 283 |
+
|
| 284 |
+
provider = provider or FrontEndProvider(repo_owner, repo_name)
|
| 285 |
+
release = provider.get_release(version)
|
| 286 |
+
|
| 287 |
+
semantic_version = release["tag_name"].lstrip("v")
|
| 288 |
+
web_root = str(
|
| 289 |
+
Path(cls.CUSTOM_FRONTENDS_ROOT) / provider.folder_name / semantic_version
|
| 290 |
+
)
|
| 291 |
+
if not os.path.exists(web_root):
|
| 292 |
+
try:
|
| 293 |
+
os.makedirs(web_root, exist_ok=True)
|
| 294 |
+
logging.info(
|
| 295 |
+
"Downloading frontend(%s) version(%s) to (%s)",
|
| 296 |
+
provider.folder_name,
|
| 297 |
+
semantic_version,
|
| 298 |
+
web_root,
|
| 299 |
+
)
|
| 300 |
+
logging.debug(release)
|
| 301 |
+
download_release_asset_zip(release, destination_path=web_root)
|
| 302 |
+
finally:
|
| 303 |
+
# Clean up the directory if it is empty, i.e. the download failed
|
| 304 |
+
if not os.listdir(web_root):
|
| 305 |
+
os.rmdir(web_root)
|
| 306 |
+
|
| 307 |
+
return web_root
|
| 308 |
+
|
| 309 |
+
@classmethod
|
| 310 |
+
def init_frontend(cls, version_string: str) -> str:
|
| 311 |
+
"""
|
| 312 |
+
Initializes the frontend with the specified version string.
|
| 313 |
+
|
| 314 |
+
Args:
|
| 315 |
+
version_string (str): The version string to initialize the frontend with.
|
| 316 |
+
|
| 317 |
+
Returns:
|
| 318 |
+
str: The path of the initialized frontend.
|
| 319 |
+
"""
|
| 320 |
+
try:
|
| 321 |
+
return cls.init_frontend_unsafe(version_string)
|
| 322 |
+
except Exception as e:
|
| 323 |
+
logging.error("Failed to initialize frontend: %s", e)
|
| 324 |
+
logging.info("Falling back to the default frontend.")
|
| 325 |
+
check_frontend_version()
|
| 326 |
+
return cls.default_frontend_path()
|
app/logger.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import deque
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
import io
|
| 4 |
+
import logging
|
| 5 |
+
import sys
|
| 6 |
+
import threading
|
| 7 |
+
|
| 8 |
+
logs = None
|
| 9 |
+
stdout_interceptor = None
|
| 10 |
+
stderr_interceptor = None
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class LogInterceptor(io.TextIOWrapper):
|
| 14 |
+
def __init__(self, stream, *args, **kwargs):
|
| 15 |
+
buffer = stream.buffer
|
| 16 |
+
encoding = stream.encoding
|
| 17 |
+
super().__init__(buffer, *args, **kwargs, encoding=encoding, line_buffering=stream.line_buffering)
|
| 18 |
+
self._lock = threading.Lock()
|
| 19 |
+
self._flush_callbacks = []
|
| 20 |
+
self._logs_since_flush = []
|
| 21 |
+
|
| 22 |
+
def write(self, data):
|
| 23 |
+
entry = {"t": datetime.now().isoformat(), "m": data}
|
| 24 |
+
with self._lock:
|
| 25 |
+
self._logs_since_flush.append(entry)
|
| 26 |
+
|
| 27 |
+
# Simple handling for cr to overwrite the last output if it isnt a full line
|
| 28 |
+
# else logs just get full of progress messages
|
| 29 |
+
if isinstance(data, str) and data.startswith("\r") and not logs[-1]["m"].endswith("\n"):
|
| 30 |
+
logs.pop()
|
| 31 |
+
logs.append(entry)
|
| 32 |
+
super().write(data)
|
| 33 |
+
|
| 34 |
+
def flush(self):
|
| 35 |
+
super().flush()
|
| 36 |
+
for cb in self._flush_callbacks:
|
| 37 |
+
cb(self._logs_since_flush)
|
| 38 |
+
self._logs_since_flush = []
|
| 39 |
+
|
| 40 |
+
def on_flush(self, callback):
|
| 41 |
+
self._flush_callbacks.append(callback)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def get_logs():
|
| 45 |
+
return logs
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def on_flush(callback):
|
| 49 |
+
if stdout_interceptor is not None:
|
| 50 |
+
stdout_interceptor.on_flush(callback)
|
| 51 |
+
if stderr_interceptor is not None:
|
| 52 |
+
stderr_interceptor.on_flush(callback)
|
| 53 |
+
|
| 54 |
+
def setup_logger(log_level: str = 'INFO', capacity: int = 300, use_stdout: bool = False):
|
| 55 |
+
global logs
|
| 56 |
+
if logs:
|
| 57 |
+
return
|
| 58 |
+
|
| 59 |
+
# Override output streams and log to buffer
|
| 60 |
+
logs = deque(maxlen=capacity)
|
| 61 |
+
|
| 62 |
+
global stdout_interceptor
|
| 63 |
+
global stderr_interceptor
|
| 64 |
+
stdout_interceptor = sys.stdout = LogInterceptor(sys.stdout)
|
| 65 |
+
stderr_interceptor = sys.stderr = LogInterceptor(sys.stderr)
|
| 66 |
+
|
| 67 |
+
# Setup default global logger
|
| 68 |
+
logger = logging.getLogger()
|
| 69 |
+
logger.setLevel(log_level)
|
| 70 |
+
|
| 71 |
+
stream_handler = logging.StreamHandler()
|
| 72 |
+
stream_handler.setFormatter(logging.Formatter("%(message)s"))
|
| 73 |
+
|
| 74 |
+
if use_stdout:
|
| 75 |
+
# Only errors and critical to stderr
|
| 76 |
+
stream_handler.addFilter(lambda record: not record.levelno < logging.ERROR)
|
| 77 |
+
|
| 78 |
+
# Lesser to stdout
|
| 79 |
+
stdout_handler = logging.StreamHandler(sys.stdout)
|
| 80 |
+
stdout_handler.setFormatter(logging.Formatter("%(message)s"))
|
| 81 |
+
stdout_handler.addFilter(lambda record: record.levelno < logging.ERROR)
|
| 82 |
+
logger.addHandler(stdout_handler)
|
| 83 |
+
|
| 84 |
+
logger.addHandler(stream_handler)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
STARTUP_WARNINGS = []
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def log_startup_warning(msg):
|
| 91 |
+
logging.warning(msg)
|
| 92 |
+
STARTUP_WARNINGS.append(msg)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def print_startup_warnings():
|
| 96 |
+
for s in STARTUP_WARNINGS:
|
| 97 |
+
logging.warning(s)
|
| 98 |
+
STARTUP_WARNINGS.clear()
|
app/model_manager.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import base64
|
| 5 |
+
import json
|
| 6 |
+
import time
|
| 7 |
+
import logging
|
| 8 |
+
import folder_paths
|
| 9 |
+
import glob
|
| 10 |
+
import comfy.utils
|
| 11 |
+
from aiohttp import web
|
| 12 |
+
from PIL import Image
|
| 13 |
+
from io import BytesIO
|
| 14 |
+
from folder_paths import map_legacy, filter_files_extensions, filter_files_content_types
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class ModelFileManager:
|
| 18 |
+
def __init__(self) -> None:
|
| 19 |
+
self.cache: dict[str, tuple[list[dict], dict[str, float], float]] = {}
|
| 20 |
+
|
| 21 |
+
def get_cache(self, key: str, default=None) -> tuple[list[dict], dict[str, float], float] | None:
|
| 22 |
+
return self.cache.get(key, default)
|
| 23 |
+
|
| 24 |
+
def set_cache(self, key: str, value: tuple[list[dict], dict[str, float], float]):
|
| 25 |
+
self.cache[key] = value
|
| 26 |
+
|
| 27 |
+
def clear_cache(self):
|
| 28 |
+
self.cache.clear()
|
| 29 |
+
|
| 30 |
+
def add_routes(self, routes):
|
| 31 |
+
# NOTE: This is an experiment to replace `/models`
|
| 32 |
+
@routes.get("/experiment/models")
|
| 33 |
+
async def get_model_folders(request):
|
| 34 |
+
model_types = list(folder_paths.folder_names_and_paths.keys())
|
| 35 |
+
folder_black_list = ["configs", "custom_nodes"]
|
| 36 |
+
output_folders: list[dict] = []
|
| 37 |
+
for folder in model_types:
|
| 38 |
+
if folder in folder_black_list:
|
| 39 |
+
continue
|
| 40 |
+
output_folders.append({"name": folder, "folders": folder_paths.get_folder_paths(folder)})
|
| 41 |
+
return web.json_response(output_folders)
|
| 42 |
+
|
| 43 |
+
# NOTE: This is an experiment to replace `/models/{folder}`
|
| 44 |
+
@routes.get("/experiment/models/{folder}")
|
| 45 |
+
async def get_all_models(request):
|
| 46 |
+
folder = request.match_info.get("folder", None)
|
| 47 |
+
if not folder in folder_paths.folder_names_and_paths:
|
| 48 |
+
return web.Response(status=404)
|
| 49 |
+
files = self.get_model_file_list(folder)
|
| 50 |
+
return web.json_response(files)
|
| 51 |
+
|
| 52 |
+
@routes.get("/experiment/models/preview/{folder}/{path_index}/{filename:.*}")
|
| 53 |
+
async def get_model_preview(request):
|
| 54 |
+
folder_name = request.match_info.get("folder", None)
|
| 55 |
+
path_index = int(request.match_info.get("path_index", None))
|
| 56 |
+
filename = request.match_info.get("filename", None)
|
| 57 |
+
|
| 58 |
+
if not folder_name in folder_paths.folder_names_and_paths:
|
| 59 |
+
return web.Response(status=404)
|
| 60 |
+
|
| 61 |
+
folders = folder_paths.folder_names_and_paths[folder_name]
|
| 62 |
+
folder = folders[0][path_index]
|
| 63 |
+
full_filename = os.path.join(folder, filename)
|
| 64 |
+
|
| 65 |
+
previews = self.get_model_previews(full_filename)
|
| 66 |
+
default_preview = previews[0] if len(previews) > 0 else None
|
| 67 |
+
if default_preview is None or (isinstance(default_preview, str) and not os.path.isfile(default_preview)):
|
| 68 |
+
return web.Response(status=404)
|
| 69 |
+
|
| 70 |
+
try:
|
| 71 |
+
with Image.open(default_preview) as img:
|
| 72 |
+
img_bytes = BytesIO()
|
| 73 |
+
img.save(img_bytes, format="WEBP")
|
| 74 |
+
img_bytes.seek(0)
|
| 75 |
+
return web.Response(body=img_bytes.getvalue(), content_type="image/webp")
|
| 76 |
+
except:
|
| 77 |
+
return web.Response(status=404)
|
| 78 |
+
|
| 79 |
+
def get_model_file_list(self, folder_name: str):
|
| 80 |
+
folder_name = map_legacy(folder_name)
|
| 81 |
+
folders = folder_paths.folder_names_and_paths[folder_name]
|
| 82 |
+
output_list: list[dict] = []
|
| 83 |
+
|
| 84 |
+
for index, folder in enumerate(folders[0]):
|
| 85 |
+
if not os.path.isdir(folder):
|
| 86 |
+
continue
|
| 87 |
+
out = self.cache_model_file_list_(folder)
|
| 88 |
+
if out is None:
|
| 89 |
+
out = self.recursive_search_models_(folder, index)
|
| 90 |
+
self.set_cache(folder, out)
|
| 91 |
+
output_list.extend(out[0])
|
| 92 |
+
|
| 93 |
+
return output_list
|
| 94 |
+
|
| 95 |
+
def cache_model_file_list_(self, folder: str):
|
| 96 |
+
model_file_list_cache = self.get_cache(folder)
|
| 97 |
+
|
| 98 |
+
if model_file_list_cache is None:
|
| 99 |
+
return None
|
| 100 |
+
if not os.path.isdir(folder):
|
| 101 |
+
return None
|
| 102 |
+
if os.path.getmtime(folder) != model_file_list_cache[1]:
|
| 103 |
+
return None
|
| 104 |
+
for x in model_file_list_cache[1]:
|
| 105 |
+
time_modified = model_file_list_cache[1][x]
|
| 106 |
+
folder = x
|
| 107 |
+
if os.path.getmtime(folder) != time_modified:
|
| 108 |
+
return None
|
| 109 |
+
|
| 110 |
+
return model_file_list_cache
|
| 111 |
+
|
| 112 |
+
def recursive_search_models_(self, directory: str, pathIndex: int) -> tuple[list[str], dict[str, float], float]:
|
| 113 |
+
if not os.path.isdir(directory):
|
| 114 |
+
return [], {}, time.perf_counter()
|
| 115 |
+
|
| 116 |
+
excluded_dir_names = [".git"]
|
| 117 |
+
# TODO use settings
|
| 118 |
+
include_hidden_files = False
|
| 119 |
+
|
| 120 |
+
result: list[str] = []
|
| 121 |
+
dirs: dict[str, float] = {}
|
| 122 |
+
|
| 123 |
+
for dirpath, subdirs, filenames in os.walk(directory, followlinks=True, topdown=True):
|
| 124 |
+
subdirs[:] = [d for d in subdirs if d not in excluded_dir_names]
|
| 125 |
+
if not include_hidden_files:
|
| 126 |
+
subdirs[:] = [d for d in subdirs if not d.startswith(".")]
|
| 127 |
+
filenames = [f for f in filenames if not f.startswith(".")]
|
| 128 |
+
|
| 129 |
+
filenames = filter_files_extensions(filenames, folder_paths.supported_pt_extensions)
|
| 130 |
+
|
| 131 |
+
for file_name in filenames:
|
| 132 |
+
try:
|
| 133 |
+
relative_path = os.path.relpath(os.path.join(dirpath, file_name), directory)
|
| 134 |
+
result.append(relative_path)
|
| 135 |
+
except:
|
| 136 |
+
logging.warning(f"Warning: Unable to access {file_name}. Skipping this file.")
|
| 137 |
+
continue
|
| 138 |
+
|
| 139 |
+
for d in subdirs:
|
| 140 |
+
path: str = os.path.join(dirpath, d)
|
| 141 |
+
try:
|
| 142 |
+
dirs[path] = os.path.getmtime(path)
|
| 143 |
+
except FileNotFoundError:
|
| 144 |
+
logging.warning(f"Warning: Unable to access {path}. Skipping this path.")
|
| 145 |
+
continue
|
| 146 |
+
|
| 147 |
+
return [{"name": f, "pathIndex": pathIndex} for f in result], dirs, time.perf_counter()
|
| 148 |
+
|
| 149 |
+
def get_model_previews(self, filepath: str) -> list[str | BytesIO]:
|
| 150 |
+
dirname = os.path.dirname(filepath)
|
| 151 |
+
|
| 152 |
+
if not os.path.exists(dirname):
|
| 153 |
+
return []
|
| 154 |
+
|
| 155 |
+
basename = os.path.splitext(filepath)[0]
|
| 156 |
+
match_files = glob.glob(f"{basename}.*", recursive=False)
|
| 157 |
+
image_files = filter_files_content_types(match_files, "image")
|
| 158 |
+
safetensors_file = next(filter(lambda x: x.endswith(".safetensors"), match_files), None)
|
| 159 |
+
safetensors_metadata = {}
|
| 160 |
+
|
| 161 |
+
result: list[str | BytesIO] = []
|
| 162 |
+
|
| 163 |
+
for filename in image_files:
|
| 164 |
+
_basename = os.path.splitext(filename)[0]
|
| 165 |
+
if _basename == basename:
|
| 166 |
+
result.append(filename)
|
| 167 |
+
if _basename == f"{basename}.preview":
|
| 168 |
+
result.append(filename)
|
| 169 |
+
|
| 170 |
+
if safetensors_file:
|
| 171 |
+
safetensors_filepath = os.path.join(dirname, safetensors_file)
|
| 172 |
+
header = comfy.utils.safetensors_header(safetensors_filepath, max_size=8*1024*1024)
|
| 173 |
+
if header:
|
| 174 |
+
safetensors_metadata = json.loads(header)
|
| 175 |
+
safetensors_images = safetensors_metadata.get("__metadata__", {}).get("ssmd_cover_images", None)
|
| 176 |
+
if safetensors_images:
|
| 177 |
+
safetensors_images = json.loads(safetensors_images)
|
| 178 |
+
for image in safetensors_images:
|
| 179 |
+
result.append(BytesIO(base64.b64decode(image)))
|
| 180 |
+
|
| 181 |
+
return result
|
| 182 |
+
|
| 183 |
+
def __exit__(self, exc_type, exc_value, traceback):
|
| 184 |
+
self.clear_cache()
|
app/user_manager.py
ADDED
|
@@ -0,0 +1,436 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
import re
|
| 5 |
+
import uuid
|
| 6 |
+
import glob
|
| 7 |
+
import shutil
|
| 8 |
+
import logging
|
| 9 |
+
from aiohttp import web
|
| 10 |
+
from urllib import parse
|
| 11 |
+
from comfy.cli_args import args
|
| 12 |
+
import folder_paths
|
| 13 |
+
from .app_settings import AppSettings
|
| 14 |
+
from typing import TypedDict
|
| 15 |
+
|
| 16 |
+
default_user = "default"
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class FileInfo(TypedDict):
|
| 20 |
+
path: str
|
| 21 |
+
size: int
|
| 22 |
+
modified: int
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def get_file_info(path: str, relative_to: str) -> FileInfo:
|
| 26 |
+
return {
|
| 27 |
+
"path": os.path.relpath(path, relative_to).replace(os.sep, '/'),
|
| 28 |
+
"size": os.path.getsize(path),
|
| 29 |
+
"modified": os.path.getmtime(path)
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class UserManager():
|
| 34 |
+
def __init__(self):
|
| 35 |
+
user_directory = folder_paths.get_user_directory()
|
| 36 |
+
|
| 37 |
+
self.settings = AppSettings(self)
|
| 38 |
+
if not os.path.exists(user_directory):
|
| 39 |
+
os.makedirs(user_directory, exist_ok=True)
|
| 40 |
+
if not args.multi_user:
|
| 41 |
+
logging.warning("****** User settings have been changed to be stored on the server instead of browser storage. ******")
|
| 42 |
+
logging.warning("****** For multi-user setups add the --multi-user CLI argument to enable multiple user profiles. ******")
|
| 43 |
+
|
| 44 |
+
if args.multi_user:
|
| 45 |
+
if os.path.isfile(self.get_users_file()):
|
| 46 |
+
with open(self.get_users_file()) as f:
|
| 47 |
+
self.users = json.load(f)
|
| 48 |
+
else:
|
| 49 |
+
self.users = {}
|
| 50 |
+
else:
|
| 51 |
+
self.users = {"default": "default"}
|
| 52 |
+
|
| 53 |
+
def get_users_file(self):
|
| 54 |
+
return os.path.join(folder_paths.get_user_directory(), "users.json")
|
| 55 |
+
|
| 56 |
+
def get_request_user_id(self, request):
|
| 57 |
+
user = "default"
|
| 58 |
+
if args.multi_user and "comfy-user" in request.headers:
|
| 59 |
+
user = request.headers["comfy-user"]
|
| 60 |
+
|
| 61 |
+
if user not in self.users:
|
| 62 |
+
raise KeyError("Unknown user: " + user)
|
| 63 |
+
|
| 64 |
+
return user
|
| 65 |
+
|
| 66 |
+
def get_request_user_filepath(self, request, file, type="userdata", create_dir=True):
|
| 67 |
+
user_directory = folder_paths.get_user_directory()
|
| 68 |
+
|
| 69 |
+
if type == "userdata":
|
| 70 |
+
root_dir = user_directory
|
| 71 |
+
else:
|
| 72 |
+
raise KeyError("Unknown filepath type:" + type)
|
| 73 |
+
|
| 74 |
+
user = self.get_request_user_id(request)
|
| 75 |
+
path = user_root = os.path.abspath(os.path.join(root_dir, user))
|
| 76 |
+
|
| 77 |
+
# prevent leaving /{type}
|
| 78 |
+
if os.path.commonpath((root_dir, user_root)) != root_dir:
|
| 79 |
+
return None
|
| 80 |
+
|
| 81 |
+
if file is not None:
|
| 82 |
+
# Check if filename is url encoded
|
| 83 |
+
if "%" in file:
|
| 84 |
+
file = parse.unquote(file)
|
| 85 |
+
|
| 86 |
+
# prevent leaving /{type}/{user}
|
| 87 |
+
path = os.path.abspath(os.path.join(user_root, file))
|
| 88 |
+
if os.path.commonpath((user_root, path)) != user_root:
|
| 89 |
+
return None
|
| 90 |
+
|
| 91 |
+
parent = os.path.split(path)[0]
|
| 92 |
+
|
| 93 |
+
if create_dir and not os.path.exists(parent):
|
| 94 |
+
os.makedirs(parent, exist_ok=True)
|
| 95 |
+
|
| 96 |
+
return path
|
| 97 |
+
|
| 98 |
+
def add_user(self, name):
|
| 99 |
+
name = name.strip()
|
| 100 |
+
if not name:
|
| 101 |
+
raise ValueError("username not provided")
|
| 102 |
+
user_id = re.sub("[^a-zA-Z0-9-_]+", '-', name)
|
| 103 |
+
user_id = user_id + "_" + str(uuid.uuid4())
|
| 104 |
+
|
| 105 |
+
self.users[user_id] = name
|
| 106 |
+
|
| 107 |
+
with open(self.get_users_file(), "w") as f:
|
| 108 |
+
json.dump(self.users, f)
|
| 109 |
+
|
| 110 |
+
return user_id
|
| 111 |
+
|
| 112 |
+
def add_routes(self, routes):
|
| 113 |
+
self.settings.add_routes(routes)
|
| 114 |
+
|
| 115 |
+
@routes.get("/users")
|
| 116 |
+
async def get_users(request):
|
| 117 |
+
if args.multi_user:
|
| 118 |
+
return web.json_response({"storage": "server", "users": self.users})
|
| 119 |
+
else:
|
| 120 |
+
user_dir = self.get_request_user_filepath(request, None, create_dir=False)
|
| 121 |
+
return web.json_response({
|
| 122 |
+
"storage": "server",
|
| 123 |
+
"migrated": os.path.exists(user_dir)
|
| 124 |
+
})
|
| 125 |
+
|
| 126 |
+
@routes.post("/users")
|
| 127 |
+
async def post_users(request):
|
| 128 |
+
body = await request.json()
|
| 129 |
+
username = body["username"]
|
| 130 |
+
if username in self.users.values():
|
| 131 |
+
return web.json_response({"error": "Duplicate username."}, status=400)
|
| 132 |
+
|
| 133 |
+
user_id = self.add_user(username)
|
| 134 |
+
return web.json_response(user_id)
|
| 135 |
+
|
| 136 |
+
@routes.get("/userdata")
|
| 137 |
+
async def listuserdata(request):
|
| 138 |
+
"""
|
| 139 |
+
List user data files in a specified directory.
|
| 140 |
+
|
| 141 |
+
This endpoint allows listing files in a user's data directory, with options for recursion,
|
| 142 |
+
full file information, and path splitting.
|
| 143 |
+
|
| 144 |
+
Query Parameters:
|
| 145 |
+
- dir (required): The directory to list files from.
|
| 146 |
+
- recurse (optional): If "true", recursively list files in subdirectories.
|
| 147 |
+
- full_info (optional): If "true", return detailed file information (path, size, modified time).
|
| 148 |
+
- split (optional): If "true", split file paths into components (only applies when full_info is false).
|
| 149 |
+
|
| 150 |
+
Returns:
|
| 151 |
+
- 400: If 'dir' parameter is missing.
|
| 152 |
+
- 403: If the requested path is not allowed.
|
| 153 |
+
- 404: If the requested directory does not exist.
|
| 154 |
+
- 200: JSON response with the list of files or file information.
|
| 155 |
+
|
| 156 |
+
The response format depends on the query parameters:
|
| 157 |
+
- Default: List of relative file paths.
|
| 158 |
+
- full_info=true: List of dictionaries with file details.
|
| 159 |
+
- split=true (and full_info=false): List of lists, each containing path components.
|
| 160 |
+
"""
|
| 161 |
+
directory = request.rel_url.query.get('dir', '')
|
| 162 |
+
if not directory:
|
| 163 |
+
return web.Response(status=400, text="Directory not provided")
|
| 164 |
+
|
| 165 |
+
path = self.get_request_user_filepath(request, directory)
|
| 166 |
+
if not path:
|
| 167 |
+
return web.Response(status=403, text="Invalid directory")
|
| 168 |
+
|
| 169 |
+
if not os.path.exists(path):
|
| 170 |
+
return web.Response(status=404, text="Directory not found")
|
| 171 |
+
|
| 172 |
+
recurse = request.rel_url.query.get('recurse', '').lower() == "true"
|
| 173 |
+
full_info = request.rel_url.query.get('full_info', '').lower() == "true"
|
| 174 |
+
split_path = request.rel_url.query.get('split', '').lower() == "true"
|
| 175 |
+
|
| 176 |
+
# Use different patterns based on whether we're recursing or not
|
| 177 |
+
if recurse:
|
| 178 |
+
pattern = os.path.join(glob.escape(path), '**', '*')
|
| 179 |
+
else:
|
| 180 |
+
pattern = os.path.join(glob.escape(path), '*')
|
| 181 |
+
|
| 182 |
+
def process_full_path(full_path: str) -> FileInfo | str | list[str]:
|
| 183 |
+
if full_info:
|
| 184 |
+
return get_file_info(full_path, path)
|
| 185 |
+
|
| 186 |
+
rel_path = os.path.relpath(full_path, path).replace(os.sep, '/')
|
| 187 |
+
if split_path:
|
| 188 |
+
return [rel_path] + rel_path.split('/')
|
| 189 |
+
|
| 190 |
+
return rel_path
|
| 191 |
+
|
| 192 |
+
results = [
|
| 193 |
+
process_full_path(full_path)
|
| 194 |
+
for full_path in glob.glob(pattern, recursive=recurse)
|
| 195 |
+
if os.path.isfile(full_path)
|
| 196 |
+
]
|
| 197 |
+
|
| 198 |
+
return web.json_response(results)
|
| 199 |
+
|
| 200 |
+
@routes.get("/v2/userdata")
|
| 201 |
+
async def list_userdata_v2(request):
|
| 202 |
+
"""
|
| 203 |
+
List files and directories in a user's data directory.
|
| 204 |
+
|
| 205 |
+
This endpoint provides a structured listing of contents within a specified
|
| 206 |
+
subdirectory of the user's data storage.
|
| 207 |
+
|
| 208 |
+
Query Parameters:
|
| 209 |
+
- path (optional): The relative path within the user's data directory
|
| 210 |
+
to list. Defaults to the root ('').
|
| 211 |
+
|
| 212 |
+
Returns:
|
| 213 |
+
- 400: If the requested path is invalid, outside the user's data directory, or is not a directory.
|
| 214 |
+
- 404: If the requested path does not exist.
|
| 215 |
+
- 403: If the user is invalid.
|
| 216 |
+
- 500: If there is an error reading the directory contents.
|
| 217 |
+
- 200: JSON response containing a list of file and directory objects.
|
| 218 |
+
Each object includes:
|
| 219 |
+
- name: The name of the file or directory.
|
| 220 |
+
- type: 'file' or 'directory'.
|
| 221 |
+
- path: The relative path from the user's data root.
|
| 222 |
+
- size (for files): The size in bytes.
|
| 223 |
+
- modified (for files): The last modified timestamp (Unix epoch).
|
| 224 |
+
"""
|
| 225 |
+
requested_rel_path = request.rel_url.query.get('path', '')
|
| 226 |
+
|
| 227 |
+
# URL-decode the path parameter
|
| 228 |
+
try:
|
| 229 |
+
requested_rel_path = parse.unquote(requested_rel_path)
|
| 230 |
+
except Exception as e:
|
| 231 |
+
logging.warning(f"Failed to decode path parameter: {requested_rel_path}, Error: {e}")
|
| 232 |
+
return web.Response(status=400, text="Invalid characters in path parameter")
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
# Check user validity and get the absolute path for the requested directory
|
| 236 |
+
try:
|
| 237 |
+
base_user_path = self.get_request_user_filepath(request, None, create_dir=False)
|
| 238 |
+
|
| 239 |
+
if requested_rel_path:
|
| 240 |
+
target_abs_path = self.get_request_user_filepath(request, requested_rel_path, create_dir=False)
|
| 241 |
+
else:
|
| 242 |
+
target_abs_path = base_user_path
|
| 243 |
+
|
| 244 |
+
except KeyError as e:
|
| 245 |
+
# Invalid user detected by get_request_user_id inside get_request_user_filepath
|
| 246 |
+
logging.warning(f"Access denied for user: {e}")
|
| 247 |
+
return web.Response(status=403, text="Invalid user specified in request")
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
if not target_abs_path:
|
| 251 |
+
# Path traversal or other issue detected by get_request_user_filepath
|
| 252 |
+
return web.Response(status=400, text="Invalid path requested")
|
| 253 |
+
|
| 254 |
+
# Handle cases where the user directory or target path doesn't exist
|
| 255 |
+
if not os.path.exists(target_abs_path):
|
| 256 |
+
# Check if it's the base user directory that's missing (new user case)
|
| 257 |
+
if target_abs_path == base_user_path:
|
| 258 |
+
# It's okay if the base user directory doesn't exist yet, return empty list
|
| 259 |
+
return web.json_response([])
|
| 260 |
+
else:
|
| 261 |
+
# A specific subdirectory was requested but doesn't exist
|
| 262 |
+
return web.Response(status=404, text="Requested path not found")
|
| 263 |
+
|
| 264 |
+
if not os.path.isdir(target_abs_path):
|
| 265 |
+
return web.Response(status=400, text="Requested path is not a directory")
|
| 266 |
+
|
| 267 |
+
results = []
|
| 268 |
+
try:
|
| 269 |
+
for root, dirs, files in os.walk(target_abs_path, topdown=True):
|
| 270 |
+
# Process directories
|
| 271 |
+
for dir_name in dirs:
|
| 272 |
+
dir_path = os.path.join(root, dir_name)
|
| 273 |
+
rel_path = os.path.relpath(dir_path, base_user_path).replace(os.sep, '/')
|
| 274 |
+
results.append({
|
| 275 |
+
"name": dir_name,
|
| 276 |
+
"path": rel_path,
|
| 277 |
+
"type": "directory"
|
| 278 |
+
})
|
| 279 |
+
|
| 280 |
+
# Process files
|
| 281 |
+
for file_name in files:
|
| 282 |
+
file_path = os.path.join(root, file_name)
|
| 283 |
+
rel_path = os.path.relpath(file_path, base_user_path).replace(os.sep, '/')
|
| 284 |
+
entry_info = {
|
| 285 |
+
"name": file_name,
|
| 286 |
+
"path": rel_path,
|
| 287 |
+
"type": "file"
|
| 288 |
+
}
|
| 289 |
+
try:
|
| 290 |
+
stats = os.stat(file_path) # Use os.stat for potentially better performance with os.walk
|
| 291 |
+
entry_info["size"] = stats.st_size
|
| 292 |
+
entry_info["modified"] = stats.st_mtime
|
| 293 |
+
except OSError as stat_error:
|
| 294 |
+
logging.warning(f"Could not stat file {file_path}: {stat_error}")
|
| 295 |
+
pass # Include file with available info
|
| 296 |
+
results.append(entry_info)
|
| 297 |
+
except OSError as e:
|
| 298 |
+
logging.error(f"Error listing directory {target_abs_path}: {e}")
|
| 299 |
+
return web.Response(status=500, text="Error reading directory contents")
|
| 300 |
+
|
| 301 |
+
# Sort results alphabetically, directories first then files
|
| 302 |
+
results.sort(key=lambda x: (x['type'] != 'directory', x['name'].lower()))
|
| 303 |
+
|
| 304 |
+
return web.json_response(results)
|
| 305 |
+
|
| 306 |
+
def get_user_data_path(request, check_exists = False, param = "file"):
|
| 307 |
+
file = request.match_info.get(param, None)
|
| 308 |
+
if not file:
|
| 309 |
+
return web.Response(status=400)
|
| 310 |
+
|
| 311 |
+
path = self.get_request_user_filepath(request, file)
|
| 312 |
+
if not path:
|
| 313 |
+
return web.Response(status=403)
|
| 314 |
+
|
| 315 |
+
if check_exists and not os.path.exists(path):
|
| 316 |
+
return web.Response(status=404)
|
| 317 |
+
|
| 318 |
+
return path
|
| 319 |
+
|
| 320 |
+
@routes.get("/userdata/{file}")
|
| 321 |
+
async def getuserdata(request):
|
| 322 |
+
path = get_user_data_path(request, check_exists=True)
|
| 323 |
+
if not isinstance(path, str):
|
| 324 |
+
return path
|
| 325 |
+
|
| 326 |
+
return web.FileResponse(path)
|
| 327 |
+
|
| 328 |
+
@routes.post("/userdata/{file}")
|
| 329 |
+
async def post_userdata(request):
|
| 330 |
+
"""
|
| 331 |
+
Upload or update a user data file.
|
| 332 |
+
|
| 333 |
+
This endpoint handles file uploads to a user's data directory, with options for
|
| 334 |
+
controlling overwrite behavior and response format.
|
| 335 |
+
|
| 336 |
+
Query Parameters:
|
| 337 |
+
- overwrite (optional): If "false", prevents overwriting existing files. Defaults to "true".
|
| 338 |
+
- full_info (optional): If "true", returns detailed file information (path, size, modified time).
|
| 339 |
+
If "false", returns only the relative file path.
|
| 340 |
+
|
| 341 |
+
Path Parameters:
|
| 342 |
+
- file: The target file path (URL encoded if necessary).
|
| 343 |
+
|
| 344 |
+
Returns:
|
| 345 |
+
- 400: If 'file' parameter is missing.
|
| 346 |
+
- 403: If the requested path is not allowed.
|
| 347 |
+
- 409: If overwrite=false and the file already exists.
|
| 348 |
+
- 200: JSON response with either:
|
| 349 |
+
- Full file information (if full_info=true)
|
| 350 |
+
- Relative file path (if full_info=false)
|
| 351 |
+
|
| 352 |
+
The request body should contain the raw file content to be written.
|
| 353 |
+
"""
|
| 354 |
+
path = get_user_data_path(request)
|
| 355 |
+
if not isinstance(path, str):
|
| 356 |
+
return path
|
| 357 |
+
|
| 358 |
+
overwrite = request.query.get("overwrite", 'true') != "false"
|
| 359 |
+
full_info = request.query.get('full_info', 'false').lower() == "true"
|
| 360 |
+
|
| 361 |
+
if not overwrite and os.path.exists(path):
|
| 362 |
+
return web.Response(status=409, text="File already exists")
|
| 363 |
+
|
| 364 |
+
body = await request.read()
|
| 365 |
+
|
| 366 |
+
with open(path, "wb") as f:
|
| 367 |
+
f.write(body)
|
| 368 |
+
|
| 369 |
+
user_path = self.get_request_user_filepath(request, None)
|
| 370 |
+
if full_info:
|
| 371 |
+
resp = get_file_info(path, user_path)
|
| 372 |
+
else:
|
| 373 |
+
resp = os.path.relpath(path, user_path)
|
| 374 |
+
|
| 375 |
+
return web.json_response(resp)
|
| 376 |
+
|
| 377 |
+
@routes.delete("/userdata/{file}")
|
| 378 |
+
async def delete_userdata(request):
|
| 379 |
+
path = get_user_data_path(request, check_exists=True)
|
| 380 |
+
if not isinstance(path, str):
|
| 381 |
+
return path
|
| 382 |
+
|
| 383 |
+
os.remove(path)
|
| 384 |
+
|
| 385 |
+
return web.Response(status=204)
|
| 386 |
+
|
| 387 |
+
@routes.post("/userdata/{file}/move/{dest}")
|
| 388 |
+
async def move_userdata(request):
|
| 389 |
+
"""
|
| 390 |
+
Move or rename a user data file.
|
| 391 |
+
|
| 392 |
+
This endpoint handles moving or renaming files within a user's data directory, with options for
|
| 393 |
+
controlling overwrite behavior and response format.
|
| 394 |
+
|
| 395 |
+
Path Parameters:
|
| 396 |
+
- file: The source file path (URL encoded if necessary)
|
| 397 |
+
- dest: The destination file path (URL encoded if necessary)
|
| 398 |
+
|
| 399 |
+
Query Parameters:
|
| 400 |
+
- overwrite (optional): If "false", prevents overwriting existing files. Defaults to "true".
|
| 401 |
+
- full_info (optional): If "true", returns detailed file information (path, size, modified time).
|
| 402 |
+
If "false", returns only the relative file path.
|
| 403 |
+
|
| 404 |
+
Returns:
|
| 405 |
+
- 400: If either 'file' or 'dest' parameter is missing
|
| 406 |
+
- 403: If either requested path is not allowed
|
| 407 |
+
- 404: If the source file does not exist
|
| 408 |
+
- 409: If overwrite=false and the destination file already exists
|
| 409 |
+
- 200: JSON response with either:
|
| 410 |
+
- Full file information (if full_info=true)
|
| 411 |
+
- Relative file path (if full_info=false)
|
| 412 |
+
"""
|
| 413 |
+
source = get_user_data_path(request, check_exists=True)
|
| 414 |
+
if not isinstance(source, str):
|
| 415 |
+
return source
|
| 416 |
+
|
| 417 |
+
dest = get_user_data_path(request, check_exists=False, param="dest")
|
| 418 |
+
if not isinstance(source, str):
|
| 419 |
+
return dest
|
| 420 |
+
|
| 421 |
+
overwrite = request.query.get("overwrite", 'true') != "false"
|
| 422 |
+
full_info = request.query.get('full_info', 'false').lower() == "true"
|
| 423 |
+
|
| 424 |
+
if not overwrite and os.path.exists(dest):
|
| 425 |
+
return web.Response(status=409, text="File already exists")
|
| 426 |
+
|
| 427 |
+
logging.info(f"moving '{source}' -> '{dest}'")
|
| 428 |
+
shutil.move(source, dest)
|
| 429 |
+
|
| 430 |
+
user_path = self.get_request_user_filepath(request, None)
|
| 431 |
+
if full_info:
|
| 432 |
+
resp = get_file_info(dest, user_path)
|
| 433 |
+
else:
|
| 434 |
+
resp = os.path.relpath(dest, user_path)
|
| 435 |
+
|
| 436 |
+
return web.json_response(resp)
|
comfy/checkpoint_pickle.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pickle
|
| 2 |
+
|
| 3 |
+
load = pickle.load
|
| 4 |
+
|
| 5 |
+
class Empty:
|
| 6 |
+
pass
|
| 7 |
+
|
| 8 |
+
class Unpickler(pickle.Unpickler):
|
| 9 |
+
def find_class(self, module, name):
|
| 10 |
+
#TODO: safe unpickle
|
| 11 |
+
if module.startswith("pytorch_lightning"):
|
| 12 |
+
return Empty
|
| 13 |
+
return super().find_class(module, name)
|
comfy/cldm/cldm.py
ADDED
|
@@ -0,0 +1,433 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#taken from: https://github.com/lllyasviel/ControlNet
|
| 2 |
+
#and modified
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
|
| 7 |
+
from ..ldm.modules.diffusionmodules.util import (
|
| 8 |
+
timestep_embedding,
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
from ..ldm.modules.attention import SpatialTransformer
|
| 12 |
+
from ..ldm.modules.diffusionmodules.openaimodel import UNetModel, TimestepEmbedSequential, ResBlock, Downsample
|
| 13 |
+
from ..ldm.util import exists
|
| 14 |
+
from .control_types import UNION_CONTROLNET_TYPES
|
| 15 |
+
from collections import OrderedDict
|
| 16 |
+
import comfy.ops
|
| 17 |
+
from comfy.ldm.modules.attention import optimized_attention
|
| 18 |
+
|
| 19 |
+
class OptimizedAttention(nn.Module):
|
| 20 |
+
def __init__(self, c, nhead, dropout=0.0, dtype=None, device=None, operations=None):
|
| 21 |
+
super().__init__()
|
| 22 |
+
self.heads = nhead
|
| 23 |
+
self.c = c
|
| 24 |
+
|
| 25 |
+
self.in_proj = operations.Linear(c, c * 3, bias=True, dtype=dtype, device=device)
|
| 26 |
+
self.out_proj = operations.Linear(c, c, bias=True, dtype=dtype, device=device)
|
| 27 |
+
|
| 28 |
+
def forward(self, x):
|
| 29 |
+
x = self.in_proj(x)
|
| 30 |
+
q, k, v = x.split(self.c, dim=2)
|
| 31 |
+
out = optimized_attention(q, k, v, self.heads)
|
| 32 |
+
return self.out_proj(out)
|
| 33 |
+
|
| 34 |
+
class QuickGELU(nn.Module):
|
| 35 |
+
def forward(self, x: torch.Tensor):
|
| 36 |
+
return x * torch.sigmoid(1.702 * x)
|
| 37 |
+
|
| 38 |
+
class ResBlockUnionControlnet(nn.Module):
|
| 39 |
+
def __init__(self, dim, nhead, dtype=None, device=None, operations=None):
|
| 40 |
+
super().__init__()
|
| 41 |
+
self.attn = OptimizedAttention(dim, nhead, dtype=dtype, device=device, operations=operations)
|
| 42 |
+
self.ln_1 = operations.LayerNorm(dim, dtype=dtype, device=device)
|
| 43 |
+
self.mlp = nn.Sequential(
|
| 44 |
+
OrderedDict([("c_fc", operations.Linear(dim, dim * 4, dtype=dtype, device=device)), ("gelu", QuickGELU()),
|
| 45 |
+
("c_proj", operations.Linear(dim * 4, dim, dtype=dtype, device=device))]))
|
| 46 |
+
self.ln_2 = operations.LayerNorm(dim, dtype=dtype, device=device)
|
| 47 |
+
|
| 48 |
+
def attention(self, x: torch.Tensor):
|
| 49 |
+
return self.attn(x)
|
| 50 |
+
|
| 51 |
+
def forward(self, x: torch.Tensor):
|
| 52 |
+
x = x + self.attention(self.ln_1(x))
|
| 53 |
+
x = x + self.mlp(self.ln_2(x))
|
| 54 |
+
return x
|
| 55 |
+
|
| 56 |
+
class ControlledUnetModel(UNetModel):
|
| 57 |
+
#implemented in the ldm unet
|
| 58 |
+
pass
|
| 59 |
+
|
| 60 |
+
class ControlNet(nn.Module):
|
| 61 |
+
def __init__(
|
| 62 |
+
self,
|
| 63 |
+
image_size,
|
| 64 |
+
in_channels,
|
| 65 |
+
model_channels,
|
| 66 |
+
hint_channels,
|
| 67 |
+
num_res_blocks,
|
| 68 |
+
dropout=0,
|
| 69 |
+
channel_mult=(1, 2, 4, 8),
|
| 70 |
+
conv_resample=True,
|
| 71 |
+
dims=2,
|
| 72 |
+
num_classes=None,
|
| 73 |
+
use_checkpoint=False,
|
| 74 |
+
dtype=torch.float32,
|
| 75 |
+
num_heads=-1,
|
| 76 |
+
num_head_channels=-1,
|
| 77 |
+
num_heads_upsample=-1,
|
| 78 |
+
use_scale_shift_norm=False,
|
| 79 |
+
resblock_updown=False,
|
| 80 |
+
use_new_attention_order=False,
|
| 81 |
+
use_spatial_transformer=False, # custom transformer support
|
| 82 |
+
transformer_depth=1, # custom transformer support
|
| 83 |
+
context_dim=None, # custom transformer support
|
| 84 |
+
n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model
|
| 85 |
+
legacy=True,
|
| 86 |
+
disable_self_attentions=None,
|
| 87 |
+
num_attention_blocks=None,
|
| 88 |
+
disable_middle_self_attn=False,
|
| 89 |
+
use_linear_in_transformer=False,
|
| 90 |
+
adm_in_channels=None,
|
| 91 |
+
transformer_depth_middle=None,
|
| 92 |
+
transformer_depth_output=None,
|
| 93 |
+
attn_precision=None,
|
| 94 |
+
union_controlnet_num_control_type=None,
|
| 95 |
+
device=None,
|
| 96 |
+
operations=comfy.ops.disable_weight_init,
|
| 97 |
+
**kwargs,
|
| 98 |
+
):
|
| 99 |
+
super().__init__()
|
| 100 |
+
assert use_spatial_transformer == True, "use_spatial_transformer has to be true"
|
| 101 |
+
if use_spatial_transformer:
|
| 102 |
+
assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...'
|
| 103 |
+
|
| 104 |
+
if context_dim is not None:
|
| 105 |
+
assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...'
|
| 106 |
+
# from omegaconf.listconfig import ListConfig
|
| 107 |
+
# if type(context_dim) == ListConfig:
|
| 108 |
+
# context_dim = list(context_dim)
|
| 109 |
+
|
| 110 |
+
if num_heads_upsample == -1:
|
| 111 |
+
num_heads_upsample = num_heads
|
| 112 |
+
|
| 113 |
+
if num_heads == -1:
|
| 114 |
+
assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set'
|
| 115 |
+
|
| 116 |
+
if num_head_channels == -1:
|
| 117 |
+
assert num_heads != -1, 'Either num_heads or num_head_channels has to be set'
|
| 118 |
+
|
| 119 |
+
self.dims = dims
|
| 120 |
+
self.image_size = image_size
|
| 121 |
+
self.in_channels = in_channels
|
| 122 |
+
self.model_channels = model_channels
|
| 123 |
+
|
| 124 |
+
if isinstance(num_res_blocks, int):
|
| 125 |
+
self.num_res_blocks = len(channel_mult) * [num_res_blocks]
|
| 126 |
+
else:
|
| 127 |
+
if len(num_res_blocks) != len(channel_mult):
|
| 128 |
+
raise ValueError("provide num_res_blocks either as an int (globally constant) or "
|
| 129 |
+
"as a list/tuple (per-level) with the same length as channel_mult")
|
| 130 |
+
self.num_res_blocks = num_res_blocks
|
| 131 |
+
|
| 132 |
+
if disable_self_attentions is not None:
|
| 133 |
+
# should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not
|
| 134 |
+
assert len(disable_self_attentions) == len(channel_mult)
|
| 135 |
+
if num_attention_blocks is not None:
|
| 136 |
+
assert len(num_attention_blocks) == len(self.num_res_blocks)
|
| 137 |
+
assert all(map(lambda i: self.num_res_blocks[i] >= num_attention_blocks[i], range(len(num_attention_blocks))))
|
| 138 |
+
|
| 139 |
+
transformer_depth = transformer_depth[:]
|
| 140 |
+
|
| 141 |
+
self.dropout = dropout
|
| 142 |
+
self.channel_mult = channel_mult
|
| 143 |
+
self.conv_resample = conv_resample
|
| 144 |
+
self.num_classes = num_classes
|
| 145 |
+
self.use_checkpoint = use_checkpoint
|
| 146 |
+
self.dtype = dtype
|
| 147 |
+
self.num_heads = num_heads
|
| 148 |
+
self.num_head_channels = num_head_channels
|
| 149 |
+
self.num_heads_upsample = num_heads_upsample
|
| 150 |
+
self.predict_codebook_ids = n_embed is not None
|
| 151 |
+
|
| 152 |
+
time_embed_dim = model_channels * 4
|
| 153 |
+
self.time_embed = nn.Sequential(
|
| 154 |
+
operations.Linear(model_channels, time_embed_dim, dtype=self.dtype, device=device),
|
| 155 |
+
nn.SiLU(),
|
| 156 |
+
operations.Linear(time_embed_dim, time_embed_dim, dtype=self.dtype, device=device),
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
if self.num_classes is not None:
|
| 160 |
+
if isinstance(self.num_classes, int):
|
| 161 |
+
self.label_emb = nn.Embedding(num_classes, time_embed_dim)
|
| 162 |
+
elif self.num_classes == "continuous":
|
| 163 |
+
self.label_emb = nn.Linear(1, time_embed_dim)
|
| 164 |
+
elif self.num_classes == "sequential":
|
| 165 |
+
assert adm_in_channels is not None
|
| 166 |
+
self.label_emb = nn.Sequential(
|
| 167 |
+
nn.Sequential(
|
| 168 |
+
operations.Linear(adm_in_channels, time_embed_dim, dtype=self.dtype, device=device),
|
| 169 |
+
nn.SiLU(),
|
| 170 |
+
operations.Linear(time_embed_dim, time_embed_dim, dtype=self.dtype, device=device),
|
| 171 |
+
)
|
| 172 |
+
)
|
| 173 |
+
else:
|
| 174 |
+
raise ValueError()
|
| 175 |
+
|
| 176 |
+
self.input_blocks = nn.ModuleList(
|
| 177 |
+
[
|
| 178 |
+
TimestepEmbedSequential(
|
| 179 |
+
operations.conv_nd(dims, in_channels, model_channels, 3, padding=1, dtype=self.dtype, device=device)
|
| 180 |
+
)
|
| 181 |
+
]
|
| 182 |
+
)
|
| 183 |
+
self.zero_convs = nn.ModuleList([self.make_zero_conv(model_channels, operations=operations, dtype=self.dtype, device=device)])
|
| 184 |
+
|
| 185 |
+
self.input_hint_block = TimestepEmbedSequential(
|
| 186 |
+
operations.conv_nd(dims, hint_channels, 16, 3, padding=1, dtype=self.dtype, device=device),
|
| 187 |
+
nn.SiLU(),
|
| 188 |
+
operations.conv_nd(dims, 16, 16, 3, padding=1, dtype=self.dtype, device=device),
|
| 189 |
+
nn.SiLU(),
|
| 190 |
+
operations.conv_nd(dims, 16, 32, 3, padding=1, stride=2, dtype=self.dtype, device=device),
|
| 191 |
+
nn.SiLU(),
|
| 192 |
+
operations.conv_nd(dims, 32, 32, 3, padding=1, dtype=self.dtype, device=device),
|
| 193 |
+
nn.SiLU(),
|
| 194 |
+
operations.conv_nd(dims, 32, 96, 3, padding=1, stride=2, dtype=self.dtype, device=device),
|
| 195 |
+
nn.SiLU(),
|
| 196 |
+
operations.conv_nd(dims, 96, 96, 3, padding=1, dtype=self.dtype, device=device),
|
| 197 |
+
nn.SiLU(),
|
| 198 |
+
operations.conv_nd(dims, 96, 256, 3, padding=1, stride=2, dtype=self.dtype, device=device),
|
| 199 |
+
nn.SiLU(),
|
| 200 |
+
operations.conv_nd(dims, 256, model_channels, 3, padding=1, dtype=self.dtype, device=device)
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
self._feature_size = model_channels
|
| 204 |
+
input_block_chans = [model_channels]
|
| 205 |
+
ch = model_channels
|
| 206 |
+
ds = 1
|
| 207 |
+
for level, mult in enumerate(channel_mult):
|
| 208 |
+
for nr in range(self.num_res_blocks[level]):
|
| 209 |
+
layers = [
|
| 210 |
+
ResBlock(
|
| 211 |
+
ch,
|
| 212 |
+
time_embed_dim,
|
| 213 |
+
dropout,
|
| 214 |
+
out_channels=mult * model_channels,
|
| 215 |
+
dims=dims,
|
| 216 |
+
use_checkpoint=use_checkpoint,
|
| 217 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
| 218 |
+
dtype=self.dtype,
|
| 219 |
+
device=device,
|
| 220 |
+
operations=operations,
|
| 221 |
+
)
|
| 222 |
+
]
|
| 223 |
+
ch = mult * model_channels
|
| 224 |
+
num_transformers = transformer_depth.pop(0)
|
| 225 |
+
if num_transformers > 0:
|
| 226 |
+
if num_head_channels == -1:
|
| 227 |
+
dim_head = ch // num_heads
|
| 228 |
+
else:
|
| 229 |
+
num_heads = ch // num_head_channels
|
| 230 |
+
dim_head = num_head_channels
|
| 231 |
+
if legacy:
|
| 232 |
+
#num_heads = 1
|
| 233 |
+
dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
|
| 234 |
+
if exists(disable_self_attentions):
|
| 235 |
+
disabled_sa = disable_self_attentions[level]
|
| 236 |
+
else:
|
| 237 |
+
disabled_sa = False
|
| 238 |
+
|
| 239 |
+
if not exists(num_attention_blocks) or nr < num_attention_blocks[level]:
|
| 240 |
+
layers.append(
|
| 241 |
+
SpatialTransformer(
|
| 242 |
+
ch, num_heads, dim_head, depth=num_transformers, context_dim=context_dim,
|
| 243 |
+
disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
|
| 244 |
+
use_checkpoint=use_checkpoint, attn_precision=attn_precision, dtype=self.dtype, device=device, operations=operations
|
| 245 |
+
)
|
| 246 |
+
)
|
| 247 |
+
self.input_blocks.append(TimestepEmbedSequential(*layers))
|
| 248 |
+
self.zero_convs.append(self.make_zero_conv(ch, operations=operations, dtype=self.dtype, device=device))
|
| 249 |
+
self._feature_size += ch
|
| 250 |
+
input_block_chans.append(ch)
|
| 251 |
+
if level != len(channel_mult) - 1:
|
| 252 |
+
out_ch = ch
|
| 253 |
+
self.input_blocks.append(
|
| 254 |
+
TimestepEmbedSequential(
|
| 255 |
+
ResBlock(
|
| 256 |
+
ch,
|
| 257 |
+
time_embed_dim,
|
| 258 |
+
dropout,
|
| 259 |
+
out_channels=out_ch,
|
| 260 |
+
dims=dims,
|
| 261 |
+
use_checkpoint=use_checkpoint,
|
| 262 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
| 263 |
+
down=True,
|
| 264 |
+
dtype=self.dtype,
|
| 265 |
+
device=device,
|
| 266 |
+
operations=operations
|
| 267 |
+
)
|
| 268 |
+
if resblock_updown
|
| 269 |
+
else Downsample(
|
| 270 |
+
ch, conv_resample, dims=dims, out_channels=out_ch, dtype=self.dtype, device=device, operations=operations
|
| 271 |
+
)
|
| 272 |
+
)
|
| 273 |
+
)
|
| 274 |
+
ch = out_ch
|
| 275 |
+
input_block_chans.append(ch)
|
| 276 |
+
self.zero_convs.append(self.make_zero_conv(ch, operations=operations, dtype=self.dtype, device=device))
|
| 277 |
+
ds *= 2
|
| 278 |
+
self._feature_size += ch
|
| 279 |
+
|
| 280 |
+
if num_head_channels == -1:
|
| 281 |
+
dim_head = ch // num_heads
|
| 282 |
+
else:
|
| 283 |
+
num_heads = ch // num_head_channels
|
| 284 |
+
dim_head = num_head_channels
|
| 285 |
+
if legacy:
|
| 286 |
+
#num_heads = 1
|
| 287 |
+
dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
|
| 288 |
+
mid_block = [
|
| 289 |
+
ResBlock(
|
| 290 |
+
ch,
|
| 291 |
+
time_embed_dim,
|
| 292 |
+
dropout,
|
| 293 |
+
dims=dims,
|
| 294 |
+
use_checkpoint=use_checkpoint,
|
| 295 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
| 296 |
+
dtype=self.dtype,
|
| 297 |
+
device=device,
|
| 298 |
+
operations=operations
|
| 299 |
+
)]
|
| 300 |
+
if transformer_depth_middle >= 0:
|
| 301 |
+
mid_block += [SpatialTransformer( # always uses a self-attn
|
| 302 |
+
ch, num_heads, dim_head, depth=transformer_depth_middle, context_dim=context_dim,
|
| 303 |
+
disable_self_attn=disable_middle_self_attn, use_linear=use_linear_in_transformer,
|
| 304 |
+
use_checkpoint=use_checkpoint, attn_precision=attn_precision, dtype=self.dtype, device=device, operations=operations
|
| 305 |
+
),
|
| 306 |
+
ResBlock(
|
| 307 |
+
ch,
|
| 308 |
+
time_embed_dim,
|
| 309 |
+
dropout,
|
| 310 |
+
dims=dims,
|
| 311 |
+
use_checkpoint=use_checkpoint,
|
| 312 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
| 313 |
+
dtype=self.dtype,
|
| 314 |
+
device=device,
|
| 315 |
+
operations=operations
|
| 316 |
+
)]
|
| 317 |
+
self.middle_block = TimestepEmbedSequential(*mid_block)
|
| 318 |
+
self.middle_block_out = self.make_zero_conv(ch, operations=operations, dtype=self.dtype, device=device)
|
| 319 |
+
self._feature_size += ch
|
| 320 |
+
|
| 321 |
+
if union_controlnet_num_control_type is not None:
|
| 322 |
+
self.num_control_type = union_controlnet_num_control_type
|
| 323 |
+
num_trans_channel = 320
|
| 324 |
+
num_trans_head = 8
|
| 325 |
+
num_trans_layer = 1
|
| 326 |
+
num_proj_channel = 320
|
| 327 |
+
# task_scale_factor = num_trans_channel ** 0.5
|
| 328 |
+
self.task_embedding = nn.Parameter(torch.empty(self.num_control_type, num_trans_channel, dtype=self.dtype, device=device))
|
| 329 |
+
|
| 330 |
+
self.transformer_layes = nn.Sequential(*[ResBlockUnionControlnet(num_trans_channel, num_trans_head, dtype=self.dtype, device=device, operations=operations) for _ in range(num_trans_layer)])
|
| 331 |
+
self.spatial_ch_projs = operations.Linear(num_trans_channel, num_proj_channel, dtype=self.dtype, device=device)
|
| 332 |
+
#-----------------------------------------------------------------------------------------------------
|
| 333 |
+
|
| 334 |
+
control_add_embed_dim = 256
|
| 335 |
+
class ControlAddEmbedding(nn.Module):
|
| 336 |
+
def __init__(self, in_dim, out_dim, num_control_type, dtype=None, device=None, operations=None):
|
| 337 |
+
super().__init__()
|
| 338 |
+
self.num_control_type = num_control_type
|
| 339 |
+
self.in_dim = in_dim
|
| 340 |
+
self.linear_1 = operations.Linear(in_dim * num_control_type, out_dim, dtype=dtype, device=device)
|
| 341 |
+
self.linear_2 = operations.Linear(out_dim, out_dim, dtype=dtype, device=device)
|
| 342 |
+
def forward(self, control_type, dtype, device):
|
| 343 |
+
c_type = torch.zeros((self.num_control_type,), device=device)
|
| 344 |
+
c_type[control_type] = 1.0
|
| 345 |
+
c_type = timestep_embedding(c_type.flatten(), self.in_dim, repeat_only=False).to(dtype).reshape((-1, self.num_control_type * self.in_dim))
|
| 346 |
+
return self.linear_2(torch.nn.functional.silu(self.linear_1(c_type)))
|
| 347 |
+
|
| 348 |
+
self.control_add_embedding = ControlAddEmbedding(control_add_embed_dim, time_embed_dim, self.num_control_type, dtype=self.dtype, device=device, operations=operations)
|
| 349 |
+
else:
|
| 350 |
+
self.task_embedding = None
|
| 351 |
+
self.control_add_embedding = None
|
| 352 |
+
|
| 353 |
+
def union_controlnet_merge(self, hint, control_type, emb, context):
|
| 354 |
+
# Equivalent to: https://github.com/xinsir6/ControlNetPlus/tree/main
|
| 355 |
+
inputs = []
|
| 356 |
+
condition_list = []
|
| 357 |
+
|
| 358 |
+
for idx in range(min(1, len(control_type))):
|
| 359 |
+
controlnet_cond = self.input_hint_block(hint[idx], emb, context)
|
| 360 |
+
feat_seq = torch.mean(controlnet_cond, dim=(2, 3))
|
| 361 |
+
if idx < len(control_type):
|
| 362 |
+
feat_seq += self.task_embedding[control_type[idx]].to(dtype=feat_seq.dtype, device=feat_seq.device)
|
| 363 |
+
|
| 364 |
+
inputs.append(feat_seq.unsqueeze(1))
|
| 365 |
+
condition_list.append(controlnet_cond)
|
| 366 |
+
|
| 367 |
+
x = torch.cat(inputs, dim=1)
|
| 368 |
+
x = self.transformer_layes(x)
|
| 369 |
+
controlnet_cond_fuser = None
|
| 370 |
+
for idx in range(len(control_type)):
|
| 371 |
+
alpha = self.spatial_ch_projs(x[:, idx])
|
| 372 |
+
alpha = alpha.unsqueeze(-1).unsqueeze(-1)
|
| 373 |
+
o = condition_list[idx] + alpha
|
| 374 |
+
if controlnet_cond_fuser is None:
|
| 375 |
+
controlnet_cond_fuser = o
|
| 376 |
+
else:
|
| 377 |
+
controlnet_cond_fuser += o
|
| 378 |
+
return controlnet_cond_fuser
|
| 379 |
+
|
| 380 |
+
def make_zero_conv(self, channels, operations=None, dtype=None, device=None):
|
| 381 |
+
return TimestepEmbedSequential(operations.conv_nd(self.dims, channels, channels, 1, padding=0, dtype=dtype, device=device))
|
| 382 |
+
|
| 383 |
+
def forward(self, x, hint, timesteps, context, y=None, **kwargs):
|
| 384 |
+
t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False).to(x.dtype)
|
| 385 |
+
emb = self.time_embed(t_emb)
|
| 386 |
+
|
| 387 |
+
guided_hint = None
|
| 388 |
+
if self.control_add_embedding is not None: #Union Controlnet
|
| 389 |
+
control_type = kwargs.get("control_type", [])
|
| 390 |
+
|
| 391 |
+
if any([c >= self.num_control_type for c in control_type]):
|
| 392 |
+
max_type = max(control_type)
|
| 393 |
+
max_type_name = {
|
| 394 |
+
v: k for k, v in UNION_CONTROLNET_TYPES.items()
|
| 395 |
+
}[max_type]
|
| 396 |
+
raise ValueError(
|
| 397 |
+
f"Control type {max_type_name}({max_type}) is out of range for the number of control types" +
|
| 398 |
+
f"({self.num_control_type}) supported.\n" +
|
| 399 |
+
"Please consider using the ProMax ControlNet Union model.\n" +
|
| 400 |
+
"https://huggingface.co/xinsir/controlnet-union-sdxl-1.0/tree/main"
|
| 401 |
+
)
|
| 402 |
+
|
| 403 |
+
emb += self.control_add_embedding(control_type, emb.dtype, emb.device)
|
| 404 |
+
if len(control_type) > 0:
|
| 405 |
+
if len(hint.shape) < 5:
|
| 406 |
+
hint = hint.unsqueeze(dim=0)
|
| 407 |
+
guided_hint = self.union_controlnet_merge(hint, control_type, emb, context)
|
| 408 |
+
|
| 409 |
+
if guided_hint is None:
|
| 410 |
+
guided_hint = self.input_hint_block(hint, emb, context)
|
| 411 |
+
|
| 412 |
+
out_output = []
|
| 413 |
+
out_middle = []
|
| 414 |
+
|
| 415 |
+
if self.num_classes is not None:
|
| 416 |
+
assert y.shape[0] == x.shape[0]
|
| 417 |
+
emb = emb + self.label_emb(y)
|
| 418 |
+
|
| 419 |
+
h = x
|
| 420 |
+
for module, zero_conv in zip(self.input_blocks, self.zero_convs):
|
| 421 |
+
if guided_hint is not None:
|
| 422 |
+
h = module(h, emb, context)
|
| 423 |
+
h += guided_hint
|
| 424 |
+
guided_hint = None
|
| 425 |
+
else:
|
| 426 |
+
h = module(h, emb, context)
|
| 427 |
+
out_output.append(zero_conv(h, emb, context))
|
| 428 |
+
|
| 429 |
+
h = self.middle_block(h, emb, context)
|
| 430 |
+
out_middle.append(self.middle_block_out(h, emb, context))
|
| 431 |
+
|
| 432 |
+
return {"middle": out_middle, "output": out_output}
|
| 433 |
+
|
comfy/cldm/control_types.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
UNION_CONTROLNET_TYPES = {
|
| 2 |
+
"openpose": 0,
|
| 3 |
+
"depth": 1,
|
| 4 |
+
"hed/pidi/scribble/ted": 2,
|
| 5 |
+
"canny/lineart/anime_lineart/mlsd": 3,
|
| 6 |
+
"normal": 4,
|
| 7 |
+
"segment": 5,
|
| 8 |
+
"tile": 6,
|
| 9 |
+
"repaint": 7,
|
| 10 |
+
}
|
comfy/cldm/dit_embedder.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from typing import List, Optional, Tuple
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
from torch import Tensor
|
| 7 |
+
|
| 8 |
+
from comfy.ldm.modules.diffusionmodules.mmdit import DismantledBlock, PatchEmbed, VectorEmbedder, TimestepEmbedder, get_2d_sincos_pos_embed_torch
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class ControlNetEmbedder(nn.Module):
|
| 12 |
+
|
| 13 |
+
def __init__(
|
| 14 |
+
self,
|
| 15 |
+
img_size: int,
|
| 16 |
+
patch_size: int,
|
| 17 |
+
in_chans: int,
|
| 18 |
+
attention_head_dim: int,
|
| 19 |
+
num_attention_heads: int,
|
| 20 |
+
adm_in_channels: int,
|
| 21 |
+
num_layers: int,
|
| 22 |
+
main_model_double: int,
|
| 23 |
+
double_y_emb: bool,
|
| 24 |
+
device: torch.device,
|
| 25 |
+
dtype: torch.dtype,
|
| 26 |
+
pos_embed_max_size: Optional[int] = None,
|
| 27 |
+
operations = None,
|
| 28 |
+
):
|
| 29 |
+
super().__init__()
|
| 30 |
+
self.main_model_double = main_model_double
|
| 31 |
+
self.dtype = dtype
|
| 32 |
+
self.hidden_size = num_attention_heads * attention_head_dim
|
| 33 |
+
self.patch_size = patch_size
|
| 34 |
+
self.x_embedder = PatchEmbed(
|
| 35 |
+
img_size=img_size,
|
| 36 |
+
patch_size=patch_size,
|
| 37 |
+
in_chans=in_chans,
|
| 38 |
+
embed_dim=self.hidden_size,
|
| 39 |
+
strict_img_size=pos_embed_max_size is None,
|
| 40 |
+
device=device,
|
| 41 |
+
dtype=dtype,
|
| 42 |
+
operations=operations,
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
self.t_embedder = TimestepEmbedder(self.hidden_size, dtype=dtype, device=device, operations=operations)
|
| 46 |
+
|
| 47 |
+
self.double_y_emb = double_y_emb
|
| 48 |
+
if self.double_y_emb:
|
| 49 |
+
self.orig_y_embedder = VectorEmbedder(
|
| 50 |
+
adm_in_channels, self.hidden_size, dtype, device, operations=operations
|
| 51 |
+
)
|
| 52 |
+
self.y_embedder = VectorEmbedder(
|
| 53 |
+
self.hidden_size, self.hidden_size, dtype, device, operations=operations
|
| 54 |
+
)
|
| 55 |
+
else:
|
| 56 |
+
self.y_embedder = VectorEmbedder(
|
| 57 |
+
adm_in_channels, self.hidden_size, dtype, device, operations=operations
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
self.transformer_blocks = nn.ModuleList(
|
| 61 |
+
DismantledBlock(
|
| 62 |
+
hidden_size=self.hidden_size, num_heads=num_attention_heads, qkv_bias=True,
|
| 63 |
+
dtype=dtype, device=device, operations=operations
|
| 64 |
+
)
|
| 65 |
+
for _ in range(num_layers)
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
# self.use_y_embedder = pooled_projection_dim != self.time_text_embed.text_embedder.linear_1.in_features
|
| 69 |
+
# TODO double check this logic when 8b
|
| 70 |
+
self.use_y_embedder = True
|
| 71 |
+
|
| 72 |
+
self.controlnet_blocks = nn.ModuleList([])
|
| 73 |
+
for _ in range(len(self.transformer_blocks)):
|
| 74 |
+
controlnet_block = operations.Linear(self.hidden_size, self.hidden_size, dtype=dtype, device=device)
|
| 75 |
+
self.controlnet_blocks.append(controlnet_block)
|
| 76 |
+
|
| 77 |
+
self.pos_embed_input = PatchEmbed(
|
| 78 |
+
img_size=img_size,
|
| 79 |
+
patch_size=patch_size,
|
| 80 |
+
in_chans=in_chans,
|
| 81 |
+
embed_dim=self.hidden_size,
|
| 82 |
+
strict_img_size=False,
|
| 83 |
+
device=device,
|
| 84 |
+
dtype=dtype,
|
| 85 |
+
operations=operations,
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
def forward(
|
| 89 |
+
self,
|
| 90 |
+
x: torch.Tensor,
|
| 91 |
+
timesteps: torch.Tensor,
|
| 92 |
+
y: Optional[torch.Tensor] = None,
|
| 93 |
+
context: Optional[torch.Tensor] = None,
|
| 94 |
+
hint = None,
|
| 95 |
+
) -> Tuple[Tensor, List[Tensor]]:
|
| 96 |
+
x_shape = list(x.shape)
|
| 97 |
+
x = self.x_embedder(x)
|
| 98 |
+
if not self.double_y_emb:
|
| 99 |
+
h = (x_shape[-2] + 1) // self.patch_size
|
| 100 |
+
w = (x_shape[-1] + 1) // self.patch_size
|
| 101 |
+
x += get_2d_sincos_pos_embed_torch(self.hidden_size, w, h, device=x.device)
|
| 102 |
+
c = self.t_embedder(timesteps, dtype=x.dtype)
|
| 103 |
+
if y is not None and self.y_embedder is not None:
|
| 104 |
+
if self.double_y_emb:
|
| 105 |
+
y = self.orig_y_embedder(y)
|
| 106 |
+
y = self.y_embedder(y)
|
| 107 |
+
c = c + y
|
| 108 |
+
|
| 109 |
+
x = x + self.pos_embed_input(hint)
|
| 110 |
+
|
| 111 |
+
block_out = ()
|
| 112 |
+
|
| 113 |
+
repeat = math.ceil(self.main_model_double / len(self.transformer_blocks))
|
| 114 |
+
for i in range(len(self.transformer_blocks)):
|
| 115 |
+
out = self.transformer_blocks[i](x, c)
|
| 116 |
+
if not self.double_y_emb:
|
| 117 |
+
x = out
|
| 118 |
+
block_out += (self.controlnet_blocks[i](out),) * repeat
|
| 119 |
+
|
| 120 |
+
return {"output": block_out}
|
comfy/cldm/mmdit.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from typing import Optional
|
| 3 |
+
import comfy.ldm.modules.diffusionmodules.mmdit
|
| 4 |
+
|
| 5 |
+
class ControlNet(comfy.ldm.modules.diffusionmodules.mmdit.MMDiT):
|
| 6 |
+
def __init__(
|
| 7 |
+
self,
|
| 8 |
+
num_blocks = None,
|
| 9 |
+
control_latent_channels = None,
|
| 10 |
+
dtype = None,
|
| 11 |
+
device = None,
|
| 12 |
+
operations = None,
|
| 13 |
+
**kwargs,
|
| 14 |
+
):
|
| 15 |
+
super().__init__(dtype=dtype, device=device, operations=operations, final_layer=False, num_blocks=num_blocks, **kwargs)
|
| 16 |
+
# controlnet_blocks
|
| 17 |
+
self.controlnet_blocks = torch.nn.ModuleList([])
|
| 18 |
+
for _ in range(len(self.joint_blocks)):
|
| 19 |
+
self.controlnet_blocks.append(operations.Linear(self.hidden_size, self.hidden_size, device=device, dtype=dtype))
|
| 20 |
+
|
| 21 |
+
if control_latent_channels is None:
|
| 22 |
+
control_latent_channels = self.in_channels
|
| 23 |
+
|
| 24 |
+
self.pos_embed_input = comfy.ldm.modules.diffusionmodules.mmdit.PatchEmbed(
|
| 25 |
+
None,
|
| 26 |
+
self.patch_size,
|
| 27 |
+
control_latent_channels,
|
| 28 |
+
self.hidden_size,
|
| 29 |
+
bias=True,
|
| 30 |
+
strict_img_size=False,
|
| 31 |
+
dtype=dtype,
|
| 32 |
+
device=device,
|
| 33 |
+
operations=operations
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
def forward(
|
| 37 |
+
self,
|
| 38 |
+
x: torch.Tensor,
|
| 39 |
+
timesteps: torch.Tensor,
|
| 40 |
+
y: Optional[torch.Tensor] = None,
|
| 41 |
+
context: Optional[torch.Tensor] = None,
|
| 42 |
+
hint = None,
|
| 43 |
+
) -> torch.Tensor:
|
| 44 |
+
|
| 45 |
+
#weird sd3 controlnet specific stuff
|
| 46 |
+
y = torch.zeros_like(y)
|
| 47 |
+
|
| 48 |
+
if self.context_processor is not None:
|
| 49 |
+
context = self.context_processor(context)
|
| 50 |
+
|
| 51 |
+
hw = x.shape[-2:]
|
| 52 |
+
x = self.x_embedder(x) + self.cropped_pos_embed(hw, device=x.device).to(dtype=x.dtype, device=x.device)
|
| 53 |
+
x += self.pos_embed_input(hint)
|
| 54 |
+
|
| 55 |
+
c = self.t_embedder(timesteps, dtype=x.dtype)
|
| 56 |
+
if y is not None and self.y_embedder is not None:
|
| 57 |
+
y = self.y_embedder(y)
|
| 58 |
+
c = c + y
|
| 59 |
+
|
| 60 |
+
if context is not None:
|
| 61 |
+
context = self.context_embedder(context)
|
| 62 |
+
|
| 63 |
+
output = []
|
| 64 |
+
|
| 65 |
+
blocks = len(self.joint_blocks)
|
| 66 |
+
for i in range(blocks):
|
| 67 |
+
context, x = self.joint_blocks[i](
|
| 68 |
+
context,
|
| 69 |
+
x,
|
| 70 |
+
c=c,
|
| 71 |
+
use_checkpoint=self.use_checkpoint,
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
out = self.controlnet_blocks[i](x)
|
| 75 |
+
count = self.depth // blocks
|
| 76 |
+
if i == blocks - 1:
|
| 77 |
+
count -= 1
|
| 78 |
+
for j in range(count):
|
| 79 |
+
output.append(out)
|
| 80 |
+
|
| 81 |
+
return {"output": output}
|
comfy/cli_args.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import enum
|
| 3 |
+
import os
|
| 4 |
+
import comfy.options
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class EnumAction(argparse.Action):
|
| 8 |
+
"""
|
| 9 |
+
Argparse action for handling Enums
|
| 10 |
+
"""
|
| 11 |
+
def __init__(self, **kwargs):
|
| 12 |
+
# Pop off the type value
|
| 13 |
+
enum_type = kwargs.pop("type", None)
|
| 14 |
+
|
| 15 |
+
# Ensure an Enum subclass is provided
|
| 16 |
+
if enum_type is None:
|
| 17 |
+
raise ValueError("type must be assigned an Enum when using EnumAction")
|
| 18 |
+
if not issubclass(enum_type, enum.Enum):
|
| 19 |
+
raise TypeError("type must be an Enum when using EnumAction")
|
| 20 |
+
|
| 21 |
+
# Generate choices from the Enum
|
| 22 |
+
choices = tuple(e.value for e in enum_type)
|
| 23 |
+
kwargs.setdefault("choices", choices)
|
| 24 |
+
kwargs.setdefault("metavar", f"[{','.join(list(choices))}]")
|
| 25 |
+
|
| 26 |
+
super(EnumAction, self).__init__(**kwargs)
|
| 27 |
+
|
| 28 |
+
self._enum = enum_type
|
| 29 |
+
|
| 30 |
+
def __call__(self, parser, namespace, values, option_string=None):
|
| 31 |
+
# Convert value back into an Enum
|
| 32 |
+
value = self._enum(values)
|
| 33 |
+
setattr(namespace, self.dest, value)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
parser = argparse.ArgumentParser()
|
| 37 |
+
|
| 38 |
+
parser.add_argument("--listen", type=str, default="127.0.0.1", metavar="IP", nargs="?", const="0.0.0.0,::", help="Specify the IP address to listen on (default: 127.0.0.1). You can give a list of ip addresses by separating them with a comma like: 127.2.2.2,127.3.3.3 If --listen is provided without an argument, it defaults to 0.0.0.0,:: (listens on all ipv4 and ipv6)")
|
| 39 |
+
parser.add_argument("--port", type=int, default=8188, help="Set the listen port.")
|
| 40 |
+
parser.add_argument("--tls-keyfile", type=str, help="Path to TLS (SSL) key file. Enables TLS, makes app accessible at https://... requires --tls-certfile to function")
|
| 41 |
+
parser.add_argument("--tls-certfile", type=str, help="Path to TLS (SSL) certificate file. Enables TLS, makes app accessible at https://... requires --tls-keyfile to function")
|
| 42 |
+
parser.add_argument("--enable-cors-header", type=str, default=None, metavar="ORIGIN", nargs="?", const="*", help="Enable CORS (Cross-Origin Resource Sharing) with optional origin or allow all with default '*'.")
|
| 43 |
+
parser.add_argument("--max-upload-size", type=float, default=100, help="Set the maximum upload size in MB.")
|
| 44 |
+
|
| 45 |
+
parser.add_argument("--base-directory", type=str, default=None, help="Set the ComfyUI base directory for models, custom_nodes, input, output, temp, and user directories.")
|
| 46 |
+
parser.add_argument("--extra-model-paths-config", type=str, default=None, metavar="PATH", nargs='+', action='append', help="Load one or more extra_model_paths.yaml files.")
|
| 47 |
+
parser.add_argument("--output-directory", type=str, default=None, help="Set the ComfyUI output directory. Overrides --base-directory.")
|
| 48 |
+
parser.add_argument("--temp-directory", type=str, default=None, help="Set the ComfyUI temp directory (default is in the ComfyUI directory). Overrides --base-directory.")
|
| 49 |
+
parser.add_argument("--input-directory", type=str, default=None, help="Set the ComfyUI input directory. Overrides --base-directory.")
|
| 50 |
+
parser.add_argument("--auto-launch", action="store_true", help="Automatically launch ComfyUI in the default browser.")
|
| 51 |
+
parser.add_argument("--disable-auto-launch", action="store_true", help="Disable auto launching the browser.")
|
| 52 |
+
parser.add_argument("--cuda-device", type=int, default=None, metavar="DEVICE_ID", help="Set the id of the cuda device this instance will use.")
|
| 53 |
+
cm_group = parser.add_mutually_exclusive_group()
|
| 54 |
+
cm_group.add_argument("--cuda-malloc", action="store_true", help="Enable cudaMallocAsync (enabled by default for torch 2.0 and up).")
|
| 55 |
+
cm_group.add_argument("--disable-cuda-malloc", action="store_true", help="Disable cudaMallocAsync.")
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
fp_group = parser.add_mutually_exclusive_group()
|
| 59 |
+
fp_group.add_argument("--force-fp32", action="store_true", help="Force fp32 (If this makes your GPU work better please report it).")
|
| 60 |
+
fp_group.add_argument("--force-fp16", action="store_true", help="Force fp16.")
|
| 61 |
+
|
| 62 |
+
fpunet_group = parser.add_mutually_exclusive_group()
|
| 63 |
+
fpunet_group.add_argument("--fp32-unet", action="store_true", help="Run the diffusion model in fp32.")
|
| 64 |
+
fpunet_group.add_argument("--fp64-unet", action="store_true", help="Run the diffusion model in fp64.")
|
| 65 |
+
fpunet_group.add_argument("--bf16-unet", action="store_true", help="Run the diffusion model in bf16.")
|
| 66 |
+
fpunet_group.add_argument("--fp16-unet", action="store_true", help="Run the diffusion model in fp16")
|
| 67 |
+
fpunet_group.add_argument("--fp8_e4m3fn-unet", action="store_true", help="Store unet weights in fp8_e4m3fn.")
|
| 68 |
+
fpunet_group.add_argument("--fp8_e5m2-unet", action="store_true", help="Store unet weights in fp8_e5m2.")
|
| 69 |
+
fpunet_group.add_argument("--fp8_e8m0fnu-unet", action="store_true", help="Store unet weights in fp8_e8m0fnu.")
|
| 70 |
+
|
| 71 |
+
fpvae_group = parser.add_mutually_exclusive_group()
|
| 72 |
+
fpvae_group.add_argument("--fp16-vae", action="store_true", help="Run the VAE in fp16, might cause black images.")
|
| 73 |
+
fpvae_group.add_argument("--fp32-vae", action="store_true", help="Run the VAE in full precision fp32.")
|
| 74 |
+
fpvae_group.add_argument("--bf16-vae", action="store_true", help="Run the VAE in bf16.")
|
| 75 |
+
|
| 76 |
+
parser.add_argument("--cpu-vae", action="store_true", help="Run the VAE on the CPU.")
|
| 77 |
+
|
| 78 |
+
fpte_group = parser.add_mutually_exclusive_group()
|
| 79 |
+
fpte_group.add_argument("--fp8_e4m3fn-text-enc", action="store_true", help="Store text encoder weights in fp8 (e4m3fn variant).")
|
| 80 |
+
fpte_group.add_argument("--fp8_e5m2-text-enc", action="store_true", help="Store text encoder weights in fp8 (e5m2 variant).")
|
| 81 |
+
fpte_group.add_argument("--fp16-text-enc", action="store_true", help="Store text encoder weights in fp16.")
|
| 82 |
+
fpte_group.add_argument("--fp32-text-enc", action="store_true", help="Store text encoder weights in fp32.")
|
| 83 |
+
fpte_group.add_argument("--bf16-text-enc", action="store_true", help="Store text encoder weights in bf16.")
|
| 84 |
+
|
| 85 |
+
parser.add_argument("--force-channels-last", action="store_true", help="Force channels last format when inferencing the models.")
|
| 86 |
+
|
| 87 |
+
parser.add_argument("--directml", type=int, nargs="?", metavar="DIRECTML_DEVICE", const=-1, help="Use torch-directml.")
|
| 88 |
+
|
| 89 |
+
parser.add_argument("--oneapi-device-selector", type=str, default=None, metavar="SELECTOR_STRING", help="Sets the oneAPI device(s) this instance will use.")
|
| 90 |
+
parser.add_argument("--disable-ipex-optimize", action="store_true", help="Disables ipex.optimize default when loading models with Intel's Extension for Pytorch.")
|
| 91 |
+
parser.add_argument("--supports-fp8-compute", action="store_true", help="ComfyUI will act like if the device supports fp8 compute.")
|
| 92 |
+
|
| 93 |
+
class LatentPreviewMethod(enum.Enum):
|
| 94 |
+
NoPreviews = "none"
|
| 95 |
+
Auto = "auto"
|
| 96 |
+
Latent2RGB = "latent2rgb"
|
| 97 |
+
TAESD = "taesd"
|
| 98 |
+
|
| 99 |
+
parser.add_argument("--preview-method", type=LatentPreviewMethod, default=LatentPreviewMethod.NoPreviews, help="Default preview method for sampler nodes.", action=EnumAction)
|
| 100 |
+
|
| 101 |
+
parser.add_argument("--preview-size", type=int, default=512, help="Sets the maximum preview size for sampler nodes.")
|
| 102 |
+
|
| 103 |
+
cache_group = parser.add_mutually_exclusive_group()
|
| 104 |
+
cache_group.add_argument("--cache-classic", action="store_true", help="Use the old style (aggressive) caching.")
|
| 105 |
+
cache_group.add_argument("--cache-lru", type=int, default=0, help="Use LRU caching with a maximum of N node results cached. May use more RAM/VRAM.")
|
| 106 |
+
cache_group.add_argument("--cache-none", action="store_true", help="Reduced RAM/VRAM usage at the expense of executing every node for each run.")
|
| 107 |
+
|
| 108 |
+
attn_group = parser.add_mutually_exclusive_group()
|
| 109 |
+
attn_group.add_argument("--use-split-cross-attention", action="store_true", help="Use the split cross attention optimization. Ignored when xformers is used.")
|
| 110 |
+
attn_group.add_argument("--use-quad-cross-attention", action="store_true", help="Use the sub-quadratic cross attention optimization . Ignored when xformers is used.")
|
| 111 |
+
attn_group.add_argument("--use-pytorch-cross-attention", action="store_true", help="Use the new pytorch 2.0 cross attention function.")
|
| 112 |
+
attn_group.add_argument("--use-sage-attention", action="store_true", help="Use sage attention.")
|
| 113 |
+
attn_group.add_argument("--use-flash-attention", action="store_true", help="Use FlashAttention.")
|
| 114 |
+
|
| 115 |
+
parser.add_argument("--disable-xformers", action="store_true", help="Disable xformers.")
|
| 116 |
+
|
| 117 |
+
upcast = parser.add_mutually_exclusive_group()
|
| 118 |
+
upcast.add_argument("--force-upcast-attention", action="store_true", help="Force enable attention upcasting, please report if it fixes black images.")
|
| 119 |
+
upcast.add_argument("--dont-upcast-attention", action="store_true", help="Disable all upcasting of attention. Should be unnecessary except for debugging.")
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
vram_group = parser.add_mutually_exclusive_group()
|
| 123 |
+
vram_group.add_argument("--gpu-only", action="store_true", help="Store and run everything (text encoders/CLIP models, etc... on the GPU).")
|
| 124 |
+
vram_group.add_argument("--highvram", action="store_true", help="By default models will be unloaded to CPU memory after being used. This option keeps them in GPU memory.")
|
| 125 |
+
vram_group.add_argument("--normalvram", action="store_true", help="Used to force normal vram use if lowvram gets automatically enabled.")
|
| 126 |
+
vram_group.add_argument("--lowvram", action="store_true", help="Split the unet in parts to use less vram.")
|
| 127 |
+
vram_group.add_argument("--novram", action="store_true", help="When lowvram isn't enough.")
|
| 128 |
+
vram_group.add_argument("--cpu", action="store_true", help="To use the CPU for everything (slow).")
|
| 129 |
+
|
| 130 |
+
parser.add_argument("--reserve-vram", type=float, default=None, help="Set the amount of vram in GB you want to reserve for use by your OS/other software. By default some amount is reserved depending on your OS.")
|
| 131 |
+
|
| 132 |
+
parser.add_argument("--async-offload", action="store_true", help="Use async weight offloading.")
|
| 133 |
+
|
| 134 |
+
parser.add_argument("--default-hashing-function", type=str, choices=['md5', 'sha1', 'sha256', 'sha512'], default='sha256', help="Allows you to choose the hash function to use for duplicate filename / contents comparison. Default is sha256.")
|
| 135 |
+
|
| 136 |
+
parser.add_argument("--disable-smart-memory", action="store_true", help="Force ComfyUI to agressively offload to regular ram instead of keeping models in vram when it can.")
|
| 137 |
+
parser.add_argument("--deterministic", action="store_true", help="Make pytorch use slower deterministic algorithms when it can. Note that this might not make images deterministic in all cases.")
|
| 138 |
+
|
| 139 |
+
class PerformanceFeature(enum.Enum):
|
| 140 |
+
Fp16Accumulation = "fp16_accumulation"
|
| 141 |
+
Fp8MatrixMultiplication = "fp8_matrix_mult"
|
| 142 |
+
CublasOps = "cublas_ops"
|
| 143 |
+
|
| 144 |
+
parser.add_argument("--fast", nargs="*", type=PerformanceFeature, help="Enable some untested and potentially quality deteriorating optimizations. --fast with no arguments enables everything. You can pass a list specific optimizations if you only want to enable specific ones. Current valid optimizations: fp16_accumulation fp8_matrix_mult cublas_ops")
|
| 145 |
+
|
| 146 |
+
parser.add_argument("--mmap-torch-files", action="store_true", help="Use mmap when loading ckpt/pt files.")
|
| 147 |
+
|
| 148 |
+
parser.add_argument("--dont-print-server", action="store_true", help="Don't print server output.")
|
| 149 |
+
parser.add_argument("--quick-test-for-ci", action="store_true", help="Quick test for CI.")
|
| 150 |
+
parser.add_argument("--windows-standalone-build", action="store_true", help="Windows standalone build: Enable convenient things that most people using the standalone windows build will probably enjoy (like auto opening the page on startup).")
|
| 151 |
+
|
| 152 |
+
parser.add_argument("--disable-metadata", action="store_true", help="Disable saving prompt metadata in files.")
|
| 153 |
+
parser.add_argument("--disable-all-custom-nodes", action="store_true", help="Disable loading all custom nodes.")
|
| 154 |
+
parser.add_argument("--whitelist-custom-nodes", type=str, nargs='+', default=[], help="Specify custom node folders to load even when --disable-all-custom-nodes is enabled.")
|
| 155 |
+
parser.add_argument("--disable-api-nodes", action="store_true", help="Disable loading all api nodes.")
|
| 156 |
+
|
| 157 |
+
parser.add_argument("--multi-user", action="store_true", help="Enables per-user storage.")
|
| 158 |
+
|
| 159 |
+
parser.add_argument("--verbose", default='INFO', const='DEBUG', nargs="?", choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], help='Set the logging level')
|
| 160 |
+
parser.add_argument("--log-stdout", action="store_true", help="Send normal process output to stdout instead of stderr (default).")
|
| 161 |
+
|
| 162 |
+
# The default built-in provider hosted under web/
|
| 163 |
+
DEFAULT_VERSION_STRING = "comfyanonymous/ComfyUI@latest"
|
| 164 |
+
|
| 165 |
+
parser.add_argument(
|
| 166 |
+
"--front-end-version",
|
| 167 |
+
type=str,
|
| 168 |
+
default=DEFAULT_VERSION_STRING,
|
| 169 |
+
help="""
|
| 170 |
+
Specifies the version of the frontend to be used. This command needs internet connectivity to query and
|
| 171 |
+
download available frontend implementations from GitHub releases.
|
| 172 |
+
|
| 173 |
+
The version string should be in the format of:
|
| 174 |
+
[repoOwner]/[repoName]@[version]
|
| 175 |
+
where version is one of: "latest" or a valid version number (e.g. "1.0.0")
|
| 176 |
+
""",
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
def is_valid_directory(path: str) -> str:
|
| 180 |
+
"""Validate if the given path is a directory, and check permissions."""
|
| 181 |
+
if not os.path.exists(path):
|
| 182 |
+
raise argparse.ArgumentTypeError(f"The path '{path}' does not exist.")
|
| 183 |
+
if not os.path.isdir(path):
|
| 184 |
+
raise argparse.ArgumentTypeError(f"'{path}' is not a directory.")
|
| 185 |
+
if not os.access(path, os.R_OK):
|
| 186 |
+
raise argparse.ArgumentTypeError(f"You do not have read permissions for '{path}'.")
|
| 187 |
+
return path
|
| 188 |
+
|
| 189 |
+
parser.add_argument(
|
| 190 |
+
"--front-end-root",
|
| 191 |
+
type=is_valid_directory,
|
| 192 |
+
default=None,
|
| 193 |
+
help="The local filesystem path to the directory where the frontend is located. Overrides --front-end-version.",
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
parser.add_argument("--user-directory", type=is_valid_directory, default=None, help="Set the ComfyUI user directory with an absolute path. Overrides --base-directory.")
|
| 197 |
+
|
| 198 |
+
parser.add_argument("--enable-compress-response-body", action="store_true", help="Enable compressing response body.")
|
| 199 |
+
|
| 200 |
+
parser.add_argument(
|
| 201 |
+
"--comfy-api-base",
|
| 202 |
+
type=str,
|
| 203 |
+
default="https://api.comfy.org",
|
| 204 |
+
help="Set the base URL for the ComfyUI API. (default: https://api.comfy.org)",
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
database_default_path = os.path.abspath(
|
| 208 |
+
os.path.join(os.path.dirname(__file__), "..", "user", "comfyui.db")
|
| 209 |
+
)
|
| 210 |
+
parser.add_argument("--database-url", type=str, default=f"sqlite:///{database_default_path}", help="Specify the database URL, e.g. for an in-memory database you can use 'sqlite:///:memory:'.")
|
| 211 |
+
|
| 212 |
+
if comfy.options.args_parsing:
|
| 213 |
+
args = parser.parse_args()
|
| 214 |
+
else:
|
| 215 |
+
args = parser.parse_args([])
|
| 216 |
+
|
| 217 |
+
if args.windows_standalone_build:
|
| 218 |
+
args.auto_launch = True
|
| 219 |
+
|
| 220 |
+
if args.disable_auto_launch:
|
| 221 |
+
args.auto_launch = False
|
| 222 |
+
|
| 223 |
+
if args.force_fp16:
|
| 224 |
+
args.fp16_unet = True
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
# '--fast' is not provided, use an empty set
|
| 228 |
+
if args.fast is None:
|
| 229 |
+
args.fast = set()
|
| 230 |
+
# '--fast' is provided with an empty list, enable all optimizations
|
| 231 |
+
elif args.fast == []:
|
| 232 |
+
args.fast = set(PerformanceFeature)
|
| 233 |
+
# '--fast' is provided with a list of performance features, use that list
|
| 234 |
+
else:
|
| 235 |
+
args.fast = set(args.fast)
|
comfy/clip_config_bigg.json
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"CLIPTextModel"
|
| 4 |
+
],
|
| 5 |
+
"attention_dropout": 0.0,
|
| 6 |
+
"bos_token_id": 0,
|
| 7 |
+
"dropout": 0.0,
|
| 8 |
+
"eos_token_id": 49407,
|
| 9 |
+
"hidden_act": "gelu",
|
| 10 |
+
"hidden_size": 1280,
|
| 11 |
+
"initializer_factor": 1.0,
|
| 12 |
+
"initializer_range": 0.02,
|
| 13 |
+
"intermediate_size": 5120,
|
| 14 |
+
"layer_norm_eps": 1e-05,
|
| 15 |
+
"max_position_embeddings": 77,
|
| 16 |
+
"model_type": "clip_text_model",
|
| 17 |
+
"num_attention_heads": 20,
|
| 18 |
+
"num_hidden_layers": 32,
|
| 19 |
+
"pad_token_id": 1,
|
| 20 |
+
"projection_dim": 1280,
|
| 21 |
+
"torch_dtype": "float32",
|
| 22 |
+
"vocab_size": 49408
|
| 23 |
+
}
|
comfy/clip_model.py
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from comfy.ldm.modules.attention import optimized_attention_for_device
|
| 3 |
+
import comfy.ops
|
| 4 |
+
|
| 5 |
+
class CLIPAttention(torch.nn.Module):
|
| 6 |
+
def __init__(self, embed_dim, heads, dtype, device, operations):
|
| 7 |
+
super().__init__()
|
| 8 |
+
|
| 9 |
+
self.heads = heads
|
| 10 |
+
self.q_proj = operations.Linear(embed_dim, embed_dim, bias=True, dtype=dtype, device=device)
|
| 11 |
+
self.k_proj = operations.Linear(embed_dim, embed_dim, bias=True, dtype=dtype, device=device)
|
| 12 |
+
self.v_proj = operations.Linear(embed_dim, embed_dim, bias=True, dtype=dtype, device=device)
|
| 13 |
+
|
| 14 |
+
self.out_proj = operations.Linear(embed_dim, embed_dim, bias=True, dtype=dtype, device=device)
|
| 15 |
+
|
| 16 |
+
def forward(self, x, mask=None, optimized_attention=None):
|
| 17 |
+
q = self.q_proj(x)
|
| 18 |
+
k = self.k_proj(x)
|
| 19 |
+
v = self.v_proj(x)
|
| 20 |
+
|
| 21 |
+
out = optimized_attention(q, k, v, self.heads, mask)
|
| 22 |
+
return self.out_proj(out)
|
| 23 |
+
|
| 24 |
+
ACTIVATIONS = {"quick_gelu": lambda a: a * torch.sigmoid(1.702 * a),
|
| 25 |
+
"gelu": torch.nn.functional.gelu,
|
| 26 |
+
"gelu_pytorch_tanh": lambda a: torch.nn.functional.gelu(a, approximate="tanh"),
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
class CLIPMLP(torch.nn.Module):
|
| 30 |
+
def __init__(self, embed_dim, intermediate_size, activation, dtype, device, operations):
|
| 31 |
+
super().__init__()
|
| 32 |
+
self.fc1 = operations.Linear(embed_dim, intermediate_size, bias=True, dtype=dtype, device=device)
|
| 33 |
+
self.activation = ACTIVATIONS[activation]
|
| 34 |
+
self.fc2 = operations.Linear(intermediate_size, embed_dim, bias=True, dtype=dtype, device=device)
|
| 35 |
+
|
| 36 |
+
def forward(self, x):
|
| 37 |
+
x = self.fc1(x)
|
| 38 |
+
x = self.activation(x)
|
| 39 |
+
x = self.fc2(x)
|
| 40 |
+
return x
|
| 41 |
+
|
| 42 |
+
class CLIPLayer(torch.nn.Module):
|
| 43 |
+
def __init__(self, embed_dim, heads, intermediate_size, intermediate_activation, dtype, device, operations):
|
| 44 |
+
super().__init__()
|
| 45 |
+
self.layer_norm1 = operations.LayerNorm(embed_dim, dtype=dtype, device=device)
|
| 46 |
+
self.self_attn = CLIPAttention(embed_dim, heads, dtype, device, operations)
|
| 47 |
+
self.layer_norm2 = operations.LayerNorm(embed_dim, dtype=dtype, device=device)
|
| 48 |
+
self.mlp = CLIPMLP(embed_dim, intermediate_size, intermediate_activation, dtype, device, operations)
|
| 49 |
+
|
| 50 |
+
def forward(self, x, mask=None, optimized_attention=None):
|
| 51 |
+
x += self.self_attn(self.layer_norm1(x), mask, optimized_attention)
|
| 52 |
+
x += self.mlp(self.layer_norm2(x))
|
| 53 |
+
return x
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class CLIPEncoder(torch.nn.Module):
|
| 57 |
+
def __init__(self, num_layers, embed_dim, heads, intermediate_size, intermediate_activation, dtype, device, operations):
|
| 58 |
+
super().__init__()
|
| 59 |
+
self.layers = torch.nn.ModuleList([CLIPLayer(embed_dim, heads, intermediate_size, intermediate_activation, dtype, device, operations) for i in range(num_layers)])
|
| 60 |
+
|
| 61 |
+
def forward(self, x, mask=None, intermediate_output=None):
|
| 62 |
+
optimized_attention = optimized_attention_for_device(x.device, mask=mask is not None, small_input=True)
|
| 63 |
+
|
| 64 |
+
if intermediate_output is not None:
|
| 65 |
+
if intermediate_output < 0:
|
| 66 |
+
intermediate_output = len(self.layers) + intermediate_output
|
| 67 |
+
|
| 68 |
+
intermediate = None
|
| 69 |
+
for i, l in enumerate(self.layers):
|
| 70 |
+
x = l(x, mask, optimized_attention)
|
| 71 |
+
if i == intermediate_output:
|
| 72 |
+
intermediate = x.clone()
|
| 73 |
+
return x, intermediate
|
| 74 |
+
|
| 75 |
+
class CLIPEmbeddings(torch.nn.Module):
|
| 76 |
+
def __init__(self, embed_dim, vocab_size=49408, num_positions=77, dtype=None, device=None, operations=None):
|
| 77 |
+
super().__init__()
|
| 78 |
+
self.token_embedding = operations.Embedding(vocab_size, embed_dim, dtype=dtype, device=device)
|
| 79 |
+
self.position_embedding = operations.Embedding(num_positions, embed_dim, dtype=dtype, device=device)
|
| 80 |
+
|
| 81 |
+
def forward(self, input_tokens, dtype=torch.float32):
|
| 82 |
+
return self.token_embedding(input_tokens, out_dtype=dtype) + comfy.ops.cast_to(self.position_embedding.weight, dtype=dtype, device=input_tokens.device)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class CLIPTextModel_(torch.nn.Module):
|
| 86 |
+
def __init__(self, config_dict, dtype, device, operations):
|
| 87 |
+
num_layers = config_dict["num_hidden_layers"]
|
| 88 |
+
embed_dim = config_dict["hidden_size"]
|
| 89 |
+
heads = config_dict["num_attention_heads"]
|
| 90 |
+
intermediate_size = config_dict["intermediate_size"]
|
| 91 |
+
intermediate_activation = config_dict["hidden_act"]
|
| 92 |
+
num_positions = config_dict["max_position_embeddings"]
|
| 93 |
+
self.eos_token_id = config_dict["eos_token_id"]
|
| 94 |
+
|
| 95 |
+
super().__init__()
|
| 96 |
+
self.embeddings = CLIPEmbeddings(embed_dim, num_positions=num_positions, dtype=dtype, device=device, operations=operations)
|
| 97 |
+
self.encoder = CLIPEncoder(num_layers, embed_dim, heads, intermediate_size, intermediate_activation, dtype, device, operations)
|
| 98 |
+
self.final_layer_norm = operations.LayerNorm(embed_dim, dtype=dtype, device=device)
|
| 99 |
+
|
| 100 |
+
def forward(self, input_tokens=None, attention_mask=None, embeds=None, num_tokens=None, intermediate_output=None, final_layer_norm_intermediate=True, dtype=torch.float32):
|
| 101 |
+
if embeds is not None:
|
| 102 |
+
x = embeds + comfy.ops.cast_to(self.embeddings.position_embedding.weight, dtype=dtype, device=embeds.device)
|
| 103 |
+
else:
|
| 104 |
+
x = self.embeddings(input_tokens, dtype=dtype)
|
| 105 |
+
|
| 106 |
+
mask = None
|
| 107 |
+
if attention_mask is not None:
|
| 108 |
+
mask = 1.0 - attention_mask.to(x.dtype).reshape((attention_mask.shape[0], 1, -1, attention_mask.shape[-1])).expand(attention_mask.shape[0], 1, attention_mask.shape[-1], attention_mask.shape[-1])
|
| 109 |
+
mask = mask.masked_fill(mask.to(torch.bool), -torch.finfo(x.dtype).max)
|
| 110 |
+
|
| 111 |
+
causal_mask = torch.full((x.shape[1], x.shape[1]), -torch.finfo(x.dtype).max, dtype=x.dtype, device=x.device).triu_(1)
|
| 112 |
+
|
| 113 |
+
if mask is not None:
|
| 114 |
+
mask += causal_mask
|
| 115 |
+
else:
|
| 116 |
+
mask = causal_mask
|
| 117 |
+
|
| 118 |
+
x, i = self.encoder(x, mask=mask, intermediate_output=intermediate_output)
|
| 119 |
+
x = self.final_layer_norm(x)
|
| 120 |
+
if i is not None and final_layer_norm_intermediate:
|
| 121 |
+
i = self.final_layer_norm(i)
|
| 122 |
+
|
| 123 |
+
if num_tokens is not None:
|
| 124 |
+
pooled_output = x[list(range(x.shape[0])), list(map(lambda a: a - 1, num_tokens))]
|
| 125 |
+
else:
|
| 126 |
+
pooled_output = x[torch.arange(x.shape[0], device=x.device), (torch.round(input_tokens).to(dtype=torch.int, device=x.device) == self.eos_token_id).int().argmax(dim=-1),]
|
| 127 |
+
return x, i, pooled_output
|
| 128 |
+
|
| 129 |
+
class CLIPTextModel(torch.nn.Module):
|
| 130 |
+
def __init__(self, config_dict, dtype, device, operations):
|
| 131 |
+
super().__init__()
|
| 132 |
+
self.num_layers = config_dict["num_hidden_layers"]
|
| 133 |
+
self.text_model = CLIPTextModel_(config_dict, dtype, device, operations)
|
| 134 |
+
embed_dim = config_dict["hidden_size"]
|
| 135 |
+
self.text_projection = operations.Linear(embed_dim, embed_dim, bias=False, dtype=dtype, device=device)
|
| 136 |
+
self.dtype = dtype
|
| 137 |
+
|
| 138 |
+
def get_input_embeddings(self):
|
| 139 |
+
return self.text_model.embeddings.token_embedding
|
| 140 |
+
|
| 141 |
+
def set_input_embeddings(self, embeddings):
|
| 142 |
+
self.text_model.embeddings.token_embedding = embeddings
|
| 143 |
+
|
| 144 |
+
def forward(self, *args, **kwargs):
|
| 145 |
+
x = self.text_model(*args, **kwargs)
|
| 146 |
+
out = self.text_projection(x[2])
|
| 147 |
+
return (x[0], x[1], out, x[2])
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class CLIPVisionEmbeddings(torch.nn.Module):
|
| 151 |
+
def __init__(self, embed_dim, num_channels=3, patch_size=14, image_size=224, model_type="", dtype=None, device=None, operations=None):
|
| 152 |
+
super().__init__()
|
| 153 |
+
|
| 154 |
+
num_patches = (image_size // patch_size) ** 2
|
| 155 |
+
if model_type == "siglip_vision_model":
|
| 156 |
+
self.class_embedding = None
|
| 157 |
+
patch_bias = True
|
| 158 |
+
else:
|
| 159 |
+
num_patches = num_patches + 1
|
| 160 |
+
self.class_embedding = torch.nn.Parameter(torch.empty(embed_dim, dtype=dtype, device=device))
|
| 161 |
+
patch_bias = False
|
| 162 |
+
|
| 163 |
+
self.patch_embedding = operations.Conv2d(
|
| 164 |
+
in_channels=num_channels,
|
| 165 |
+
out_channels=embed_dim,
|
| 166 |
+
kernel_size=patch_size,
|
| 167 |
+
stride=patch_size,
|
| 168 |
+
bias=patch_bias,
|
| 169 |
+
dtype=dtype,
|
| 170 |
+
device=device
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
self.position_embedding = operations.Embedding(num_patches, embed_dim, dtype=dtype, device=device)
|
| 174 |
+
|
| 175 |
+
def forward(self, pixel_values):
|
| 176 |
+
embeds = self.patch_embedding(pixel_values).flatten(2).transpose(1, 2)
|
| 177 |
+
if self.class_embedding is not None:
|
| 178 |
+
embeds = torch.cat([comfy.ops.cast_to_input(self.class_embedding, embeds).expand(pixel_values.shape[0], 1, -1), embeds], dim=1)
|
| 179 |
+
return embeds + comfy.ops.cast_to_input(self.position_embedding.weight, embeds)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
class CLIPVision(torch.nn.Module):
|
| 183 |
+
def __init__(self, config_dict, dtype, device, operations):
|
| 184 |
+
super().__init__()
|
| 185 |
+
num_layers = config_dict["num_hidden_layers"]
|
| 186 |
+
embed_dim = config_dict["hidden_size"]
|
| 187 |
+
heads = config_dict["num_attention_heads"]
|
| 188 |
+
intermediate_size = config_dict["intermediate_size"]
|
| 189 |
+
intermediate_activation = config_dict["hidden_act"]
|
| 190 |
+
model_type = config_dict["model_type"]
|
| 191 |
+
|
| 192 |
+
self.embeddings = CLIPVisionEmbeddings(embed_dim, config_dict["num_channels"], config_dict["patch_size"], config_dict["image_size"], model_type=model_type, dtype=dtype, device=device, operations=operations)
|
| 193 |
+
if model_type == "siglip_vision_model":
|
| 194 |
+
self.pre_layrnorm = lambda a: a
|
| 195 |
+
self.output_layernorm = True
|
| 196 |
+
else:
|
| 197 |
+
self.pre_layrnorm = operations.LayerNorm(embed_dim)
|
| 198 |
+
self.output_layernorm = False
|
| 199 |
+
self.encoder = CLIPEncoder(num_layers, embed_dim, heads, intermediate_size, intermediate_activation, dtype, device, operations)
|
| 200 |
+
self.post_layernorm = operations.LayerNorm(embed_dim)
|
| 201 |
+
|
| 202 |
+
def forward(self, pixel_values, attention_mask=None, intermediate_output=None):
|
| 203 |
+
x = self.embeddings(pixel_values)
|
| 204 |
+
x = self.pre_layrnorm(x)
|
| 205 |
+
#TODO: attention_mask?
|
| 206 |
+
x, i = self.encoder(x, mask=None, intermediate_output=intermediate_output)
|
| 207 |
+
if self.output_layernorm:
|
| 208 |
+
x = self.post_layernorm(x)
|
| 209 |
+
pooled_output = x
|
| 210 |
+
else:
|
| 211 |
+
pooled_output = self.post_layernorm(x[:, 0, :])
|
| 212 |
+
return x, i, pooled_output
|
| 213 |
+
|
| 214 |
+
class LlavaProjector(torch.nn.Module):
|
| 215 |
+
def __init__(self, in_dim, out_dim, dtype, device, operations):
|
| 216 |
+
super().__init__()
|
| 217 |
+
self.linear_1 = operations.Linear(in_dim, out_dim, bias=True, device=device, dtype=dtype)
|
| 218 |
+
self.linear_2 = operations.Linear(out_dim, out_dim, bias=True, device=device, dtype=dtype)
|
| 219 |
+
|
| 220 |
+
def forward(self, x):
|
| 221 |
+
return self.linear_2(torch.nn.functional.gelu(self.linear_1(x[:, 1:])))
|
| 222 |
+
|
| 223 |
+
class CLIPVisionModelProjection(torch.nn.Module):
|
| 224 |
+
def __init__(self, config_dict, dtype, device, operations):
|
| 225 |
+
super().__init__()
|
| 226 |
+
self.vision_model = CLIPVision(config_dict, dtype, device, operations)
|
| 227 |
+
if "projection_dim" in config_dict:
|
| 228 |
+
self.visual_projection = operations.Linear(config_dict["hidden_size"], config_dict["projection_dim"], bias=False)
|
| 229 |
+
else:
|
| 230 |
+
self.visual_projection = lambda a: a
|
| 231 |
+
|
| 232 |
+
if "llava3" == config_dict.get("projector_type", None):
|
| 233 |
+
self.multi_modal_projector = LlavaProjector(config_dict["hidden_size"], 4096, dtype, device, operations)
|
| 234 |
+
else:
|
| 235 |
+
self.multi_modal_projector = None
|
| 236 |
+
|
| 237 |
+
def forward(self, *args, **kwargs):
|
| 238 |
+
x = self.vision_model(*args, **kwargs)
|
| 239 |
+
out = self.visual_projection(x[2])
|
| 240 |
+
projected = None
|
| 241 |
+
if self.multi_modal_projector is not None:
|
| 242 |
+
projected = self.multi_modal_projector(x[1])
|
| 243 |
+
|
| 244 |
+
return (x[0], x[1], out, projected)
|
comfy/clip_vision.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .utils import load_torch_file, transformers_convert, state_dict_prefix_replace
|
| 2 |
+
import os
|
| 3 |
+
import torch
|
| 4 |
+
import json
|
| 5 |
+
import logging
|
| 6 |
+
|
| 7 |
+
import comfy.ops
|
| 8 |
+
import comfy.model_patcher
|
| 9 |
+
import comfy.model_management
|
| 10 |
+
import comfy.utils
|
| 11 |
+
import comfy.clip_model
|
| 12 |
+
import comfy.image_encoders.dino2
|
| 13 |
+
|
| 14 |
+
class Output:
|
| 15 |
+
def __getitem__(self, key):
|
| 16 |
+
return getattr(self, key)
|
| 17 |
+
def __setitem__(self, key, item):
|
| 18 |
+
setattr(self, key, item)
|
| 19 |
+
|
| 20 |
+
def clip_preprocess(image, size=224, mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711], crop=True):
|
| 21 |
+
image = image[:, :, :, :3] if image.shape[3] > 3 else image
|
| 22 |
+
mean = torch.tensor(mean, device=image.device, dtype=image.dtype)
|
| 23 |
+
std = torch.tensor(std, device=image.device, dtype=image.dtype)
|
| 24 |
+
image = image.movedim(-1, 1)
|
| 25 |
+
if not (image.shape[2] == size and image.shape[3] == size):
|
| 26 |
+
if crop:
|
| 27 |
+
scale = (size / min(image.shape[2], image.shape[3]))
|
| 28 |
+
scale_size = (round(scale * image.shape[2]), round(scale * image.shape[3]))
|
| 29 |
+
else:
|
| 30 |
+
scale_size = (size, size)
|
| 31 |
+
|
| 32 |
+
image = torch.nn.functional.interpolate(image, size=scale_size, mode="bicubic", antialias=True)
|
| 33 |
+
h = (image.shape[2] - size)//2
|
| 34 |
+
w = (image.shape[3] - size)//2
|
| 35 |
+
image = image[:,:,h:h+size,w:w+size]
|
| 36 |
+
image = torch.clip((255. * image), 0, 255).round() / 255.0
|
| 37 |
+
return (image - mean.view([3,1,1])) / std.view([3,1,1])
|
| 38 |
+
|
| 39 |
+
IMAGE_ENCODERS = {
|
| 40 |
+
"clip_vision_model": comfy.clip_model.CLIPVisionModelProjection,
|
| 41 |
+
"siglip_vision_model": comfy.clip_model.CLIPVisionModelProjection,
|
| 42 |
+
"dinov2": comfy.image_encoders.dino2.Dinov2Model,
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
class ClipVisionModel():
|
| 46 |
+
def __init__(self, json_config):
|
| 47 |
+
with open(json_config) as f:
|
| 48 |
+
config = json.load(f)
|
| 49 |
+
|
| 50 |
+
self.image_size = config.get("image_size", 224)
|
| 51 |
+
self.image_mean = config.get("image_mean", [0.48145466, 0.4578275, 0.40821073])
|
| 52 |
+
self.image_std = config.get("image_std", [0.26862954, 0.26130258, 0.27577711])
|
| 53 |
+
model_class = IMAGE_ENCODERS.get(config.get("model_type", "clip_vision_model"))
|
| 54 |
+
self.load_device = comfy.model_management.text_encoder_device()
|
| 55 |
+
offload_device = comfy.model_management.text_encoder_offload_device()
|
| 56 |
+
self.dtype = comfy.model_management.text_encoder_dtype(self.load_device)
|
| 57 |
+
self.model = model_class(config, self.dtype, offload_device, comfy.ops.manual_cast)
|
| 58 |
+
self.model.eval()
|
| 59 |
+
|
| 60 |
+
self.patcher = comfy.model_patcher.ModelPatcher(self.model, load_device=self.load_device, offload_device=offload_device)
|
| 61 |
+
|
| 62 |
+
def load_sd(self, sd):
|
| 63 |
+
return self.model.load_state_dict(sd, strict=False)
|
| 64 |
+
|
| 65 |
+
def get_sd(self):
|
| 66 |
+
return self.model.state_dict()
|
| 67 |
+
|
| 68 |
+
def encode_image(self, image, crop=True):
|
| 69 |
+
comfy.model_management.load_model_gpu(self.patcher)
|
| 70 |
+
pixel_values = clip_preprocess(image.to(self.load_device), size=self.image_size, mean=self.image_mean, std=self.image_std, crop=crop).float()
|
| 71 |
+
out = self.model(pixel_values=pixel_values, intermediate_output=-2)
|
| 72 |
+
|
| 73 |
+
outputs = Output()
|
| 74 |
+
outputs["last_hidden_state"] = out[0].to(comfy.model_management.intermediate_device())
|
| 75 |
+
outputs["image_embeds"] = out[2].to(comfy.model_management.intermediate_device())
|
| 76 |
+
outputs["penultimate_hidden_states"] = out[1].to(comfy.model_management.intermediate_device())
|
| 77 |
+
outputs["mm_projected"] = out[3]
|
| 78 |
+
return outputs
|
| 79 |
+
|
| 80 |
+
def convert_to_transformers(sd, prefix):
|
| 81 |
+
sd_k = sd.keys()
|
| 82 |
+
if "{}transformer.resblocks.0.attn.in_proj_weight".format(prefix) in sd_k:
|
| 83 |
+
keys_to_replace = {
|
| 84 |
+
"{}class_embedding".format(prefix): "vision_model.embeddings.class_embedding",
|
| 85 |
+
"{}conv1.weight".format(prefix): "vision_model.embeddings.patch_embedding.weight",
|
| 86 |
+
"{}positional_embedding".format(prefix): "vision_model.embeddings.position_embedding.weight",
|
| 87 |
+
"{}ln_post.bias".format(prefix): "vision_model.post_layernorm.bias",
|
| 88 |
+
"{}ln_post.weight".format(prefix): "vision_model.post_layernorm.weight",
|
| 89 |
+
"{}ln_pre.bias".format(prefix): "vision_model.pre_layrnorm.bias",
|
| 90 |
+
"{}ln_pre.weight".format(prefix): "vision_model.pre_layrnorm.weight",
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
for x in keys_to_replace:
|
| 94 |
+
if x in sd_k:
|
| 95 |
+
sd[keys_to_replace[x]] = sd.pop(x)
|
| 96 |
+
|
| 97 |
+
if "{}proj".format(prefix) in sd_k:
|
| 98 |
+
sd['visual_projection.weight'] = sd.pop("{}proj".format(prefix)).transpose(0, 1)
|
| 99 |
+
|
| 100 |
+
sd = transformers_convert(sd, prefix, "vision_model.", 48)
|
| 101 |
+
else:
|
| 102 |
+
replace_prefix = {prefix: ""}
|
| 103 |
+
sd = state_dict_prefix_replace(sd, replace_prefix)
|
| 104 |
+
return sd
|
| 105 |
+
|
| 106 |
+
def load_clipvision_from_sd(sd, prefix="", convert_keys=False):
|
| 107 |
+
if convert_keys:
|
| 108 |
+
sd = convert_to_transformers(sd, prefix)
|
| 109 |
+
if "vision_model.encoder.layers.47.layer_norm1.weight" in sd:
|
| 110 |
+
json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_g.json")
|
| 111 |
+
elif "vision_model.encoder.layers.30.layer_norm1.weight" in sd:
|
| 112 |
+
json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_h.json")
|
| 113 |
+
elif "vision_model.encoder.layers.22.layer_norm1.weight" in sd:
|
| 114 |
+
embed_shape = sd["vision_model.embeddings.position_embedding.weight"].shape[0]
|
| 115 |
+
if sd["vision_model.encoder.layers.0.layer_norm1.weight"].shape[0] == 1152:
|
| 116 |
+
if embed_shape == 729:
|
| 117 |
+
json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_siglip_384.json")
|
| 118 |
+
elif embed_shape == 1024:
|
| 119 |
+
json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_siglip_512.json")
|
| 120 |
+
elif embed_shape == 577:
|
| 121 |
+
if "multi_modal_projector.linear_1.bias" in sd:
|
| 122 |
+
json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_vitl_336_llava.json")
|
| 123 |
+
else:
|
| 124 |
+
json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_vitl_336.json")
|
| 125 |
+
else:
|
| 126 |
+
json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_vitl.json")
|
| 127 |
+
elif "embeddings.patch_embeddings.projection.weight" in sd:
|
| 128 |
+
json_config = os.path.join(os.path.join(os.path.dirname(os.path.realpath(__file__)), "image_encoders"), "dino2_giant.json")
|
| 129 |
+
else:
|
| 130 |
+
return None
|
| 131 |
+
|
| 132 |
+
clip = ClipVisionModel(json_config)
|
| 133 |
+
m, u = clip.load_sd(sd)
|
| 134 |
+
if len(m) > 0:
|
| 135 |
+
logging.warning("missing clip vision: {}".format(m))
|
| 136 |
+
u = set(u)
|
| 137 |
+
keys = list(sd.keys())
|
| 138 |
+
for k in keys:
|
| 139 |
+
if k not in u:
|
| 140 |
+
sd.pop(k)
|
| 141 |
+
return clip
|
| 142 |
+
|
| 143 |
+
def load(ckpt_path):
|
| 144 |
+
sd = load_torch_file(ckpt_path)
|
| 145 |
+
if "visual.transformer.resblocks.0.attn.in_proj_weight" in sd:
|
| 146 |
+
return load_clipvision_from_sd(sd, prefix="visual.", convert_keys=True)
|
| 147 |
+
else:
|
| 148 |
+
return load_clipvision_from_sd(sd)
|
comfy/clip_vision_config_g.json
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"attention_dropout": 0.0,
|
| 3 |
+
"dropout": 0.0,
|
| 4 |
+
"hidden_act": "gelu",
|
| 5 |
+
"hidden_size": 1664,
|
| 6 |
+
"image_size": 224,
|
| 7 |
+
"initializer_factor": 1.0,
|
| 8 |
+
"initializer_range": 0.02,
|
| 9 |
+
"intermediate_size": 8192,
|
| 10 |
+
"layer_norm_eps": 1e-05,
|
| 11 |
+
"model_type": "clip_vision_model",
|
| 12 |
+
"num_attention_heads": 16,
|
| 13 |
+
"num_channels": 3,
|
| 14 |
+
"num_hidden_layers": 48,
|
| 15 |
+
"patch_size": 14,
|
| 16 |
+
"projection_dim": 1280,
|
| 17 |
+
"torch_dtype": "float32"
|
| 18 |
+
}
|
comfy/clip_vision_config_h.json
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"attention_dropout": 0.0,
|
| 3 |
+
"dropout": 0.0,
|
| 4 |
+
"hidden_act": "gelu",
|
| 5 |
+
"hidden_size": 1280,
|
| 6 |
+
"image_size": 224,
|
| 7 |
+
"initializer_factor": 1.0,
|
| 8 |
+
"initializer_range": 0.02,
|
| 9 |
+
"intermediate_size": 5120,
|
| 10 |
+
"layer_norm_eps": 1e-05,
|
| 11 |
+
"model_type": "clip_vision_model",
|
| 12 |
+
"num_attention_heads": 16,
|
| 13 |
+
"num_channels": 3,
|
| 14 |
+
"num_hidden_layers": 32,
|
| 15 |
+
"patch_size": 14,
|
| 16 |
+
"projection_dim": 1024,
|
| 17 |
+
"torch_dtype": "float32"
|
| 18 |
+
}
|
comfy/clip_vision_config_vitl.json
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"attention_dropout": 0.0,
|
| 3 |
+
"dropout": 0.0,
|
| 4 |
+
"hidden_act": "quick_gelu",
|
| 5 |
+
"hidden_size": 1024,
|
| 6 |
+
"image_size": 224,
|
| 7 |
+
"initializer_factor": 1.0,
|
| 8 |
+
"initializer_range": 0.02,
|
| 9 |
+
"intermediate_size": 4096,
|
| 10 |
+
"layer_norm_eps": 1e-05,
|
| 11 |
+
"model_type": "clip_vision_model",
|
| 12 |
+
"num_attention_heads": 16,
|
| 13 |
+
"num_channels": 3,
|
| 14 |
+
"num_hidden_layers": 24,
|
| 15 |
+
"patch_size": 14,
|
| 16 |
+
"projection_dim": 768,
|
| 17 |
+
"torch_dtype": "float32"
|
| 18 |
+
}
|
comfy/clip_vision_config_vitl_336.json
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"attention_dropout": 0.0,
|
| 3 |
+
"dropout": 0.0,
|
| 4 |
+
"hidden_act": "quick_gelu",
|
| 5 |
+
"hidden_size": 1024,
|
| 6 |
+
"image_size": 336,
|
| 7 |
+
"initializer_factor": 1.0,
|
| 8 |
+
"initializer_range": 0.02,
|
| 9 |
+
"intermediate_size": 4096,
|
| 10 |
+
"layer_norm_eps": 1e-5,
|
| 11 |
+
"model_type": "clip_vision_model",
|
| 12 |
+
"num_attention_heads": 16,
|
| 13 |
+
"num_channels": 3,
|
| 14 |
+
"num_hidden_layers": 24,
|
| 15 |
+
"patch_size": 14,
|
| 16 |
+
"projection_dim": 768,
|
| 17 |
+
"torch_dtype": "float32"
|
| 18 |
+
}
|
comfy/clip_vision_config_vitl_336_llava.json
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"attention_dropout": 0.0,
|
| 3 |
+
"dropout": 0.0,
|
| 4 |
+
"hidden_act": "quick_gelu",
|
| 5 |
+
"hidden_size": 1024,
|
| 6 |
+
"image_size": 336,
|
| 7 |
+
"initializer_factor": 1.0,
|
| 8 |
+
"initializer_range": 0.02,
|
| 9 |
+
"intermediate_size": 4096,
|
| 10 |
+
"layer_norm_eps": 1e-5,
|
| 11 |
+
"model_type": "clip_vision_model",
|
| 12 |
+
"num_attention_heads": 16,
|
| 13 |
+
"num_channels": 3,
|
| 14 |
+
"num_hidden_layers": 24,
|
| 15 |
+
"patch_size": 14,
|
| 16 |
+
"projection_dim": 768,
|
| 17 |
+
"projector_type": "llava3",
|
| 18 |
+
"torch_dtype": "float32"
|
| 19 |
+
}
|
comfy/clip_vision_siglip_384.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"num_channels": 3,
|
| 3 |
+
"hidden_act": "gelu_pytorch_tanh",
|
| 4 |
+
"hidden_size": 1152,
|
| 5 |
+
"image_size": 384,
|
| 6 |
+
"intermediate_size": 4304,
|
| 7 |
+
"model_type": "siglip_vision_model",
|
| 8 |
+
"num_attention_heads": 16,
|
| 9 |
+
"num_hidden_layers": 27,
|
| 10 |
+
"patch_size": 14,
|
| 11 |
+
"image_mean": [0.5, 0.5, 0.5],
|
| 12 |
+
"image_std": [0.5, 0.5, 0.5]
|
| 13 |
+
}
|
comfy/clip_vision_siglip_512.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"num_channels": 3,
|
| 3 |
+
"hidden_act": "gelu_pytorch_tanh",
|
| 4 |
+
"hidden_size": 1152,
|
| 5 |
+
"image_size": 512,
|
| 6 |
+
"intermediate_size": 4304,
|
| 7 |
+
"model_type": "siglip_vision_model",
|
| 8 |
+
"num_attention_heads": 16,
|
| 9 |
+
"num_hidden_layers": 27,
|
| 10 |
+
"patch_size": 16,
|
| 11 |
+
"image_mean": [0.5, 0.5, 0.5],
|
| 12 |
+
"image_std": [0.5, 0.5, 0.5]
|
| 13 |
+
}
|
comfy/comfy_types/README.md
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Comfy Typing
|
| 2 |
+
## Type hinting for ComfyUI Node development
|
| 3 |
+
|
| 4 |
+
This module provides type hinting and concrete convenience types for node developers.
|
| 5 |
+
If cloned to the custom_nodes directory of ComfyUI, types can be imported using:
|
| 6 |
+
|
| 7 |
+
```python
|
| 8 |
+
from comfy.comfy_types import IO, ComfyNodeABC, CheckLazyMixin
|
| 9 |
+
|
| 10 |
+
class ExampleNode(ComfyNodeABC):
|
| 11 |
+
@classmethod
|
| 12 |
+
def INPUT_TYPES(s) -> InputTypeDict:
|
| 13 |
+
return {"required": {}}
|
| 14 |
+
```
|
| 15 |
+
|
| 16 |
+
Full example is in [examples/example_nodes.py](examples/example_nodes.py).
|
| 17 |
+
|
| 18 |
+
# Types
|
| 19 |
+
A few primary types are documented below. More complete information is available via the docstrings on each type.
|
| 20 |
+
|
| 21 |
+
## `IO`
|
| 22 |
+
|
| 23 |
+
A string enum of built-in and a few custom data types. Includes the following special types and their requisite plumbing:
|
| 24 |
+
|
| 25 |
+
- `ANY`: `"*"`
|
| 26 |
+
- `NUMBER`: `"FLOAT,INT"`
|
| 27 |
+
- `PRIMITIVE`: `"STRING,FLOAT,INT,BOOLEAN"`
|
| 28 |
+
|
| 29 |
+
## `ComfyNodeABC`
|
| 30 |
+
|
| 31 |
+
An abstract base class for nodes, offering type-hinting / autocomplete, and somewhat-alright docstrings.
|
| 32 |
+
|
| 33 |
+
### Type hinting for `INPUT_TYPES`
|
| 34 |
+
|
| 35 |
+

|
| 36 |
+
|
| 37 |
+
### `INPUT_TYPES` return dict
|
| 38 |
+
|
| 39 |
+

|
| 40 |
+
|
| 41 |
+
### Options for individual inputs
|
| 42 |
+
|
| 43 |
+

|
comfy/comfy_types/__init__.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from typing import Callable, Protocol, TypedDict, Optional, List
|
| 3 |
+
from .node_typing import IO, InputTypeDict, ComfyNodeABC, CheckLazyMixin, FileLocator
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class UnetApplyFunction(Protocol):
|
| 7 |
+
"""Function signature protocol on comfy.model_base.BaseModel.apply_model"""
|
| 8 |
+
|
| 9 |
+
def __call__(self, x: torch.Tensor, t: torch.Tensor, **kwargs) -> torch.Tensor:
|
| 10 |
+
pass
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class UnetApplyConds(TypedDict):
|
| 14 |
+
"""Optional conditions for unet apply function."""
|
| 15 |
+
|
| 16 |
+
c_concat: Optional[torch.Tensor]
|
| 17 |
+
c_crossattn: Optional[torch.Tensor]
|
| 18 |
+
control: Optional[torch.Tensor]
|
| 19 |
+
transformer_options: Optional[dict]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class UnetParams(TypedDict):
|
| 23 |
+
# Tensor of shape [B, C, H, W]
|
| 24 |
+
input: torch.Tensor
|
| 25 |
+
# Tensor of shape [B]
|
| 26 |
+
timestep: torch.Tensor
|
| 27 |
+
c: UnetApplyConds
|
| 28 |
+
# List of [0, 1], [0], [1], ...
|
| 29 |
+
# 0 means conditional, 1 means conditional unconditional
|
| 30 |
+
cond_or_uncond: List[int]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
UnetWrapperFunction = Callable[[UnetApplyFunction, UnetParams], torch.Tensor]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
__all__ = [
|
| 37 |
+
"UnetWrapperFunction",
|
| 38 |
+
UnetApplyConds.__name__,
|
| 39 |
+
UnetParams.__name__,
|
| 40 |
+
UnetApplyFunction.__name__,
|
| 41 |
+
IO.__name__,
|
| 42 |
+
InputTypeDict.__name__,
|
| 43 |
+
ComfyNodeABC.__name__,
|
| 44 |
+
CheckLazyMixin.__name__,
|
| 45 |
+
FileLocator.__name__,
|
| 46 |
+
]
|
comfy/comfy_types/examples/example_nodes.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from comfy.comfy_types import IO, ComfyNodeABC, InputTypeDict
|
| 2 |
+
from inspect import cleandoc
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class ExampleNode(ComfyNodeABC):
|
| 6 |
+
"""An example node that just adds 1 to an input integer.
|
| 7 |
+
|
| 8 |
+
* Requires a modern IDE to provide any benefit (detail: an IDE configured with analysis paths etc).
|
| 9 |
+
* This node is intended as an example for developers only.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
DESCRIPTION = cleandoc(__doc__)
|
| 13 |
+
CATEGORY = "examples"
|
| 14 |
+
|
| 15 |
+
@classmethod
|
| 16 |
+
def INPUT_TYPES(s) -> InputTypeDict:
|
| 17 |
+
return {
|
| 18 |
+
"required": {
|
| 19 |
+
"input_int": (IO.INT, {"defaultInput": True}),
|
| 20 |
+
}
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
RETURN_TYPES = (IO.INT,)
|
| 24 |
+
RETURN_NAMES = ("input_plus_one",)
|
| 25 |
+
FUNCTION = "execute"
|
| 26 |
+
|
| 27 |
+
def execute(self, input_int: int):
|
| 28 |
+
return (input_int + 1,)
|
comfy/comfy_types/examples/input_options.png
ADDED
|
comfy/comfy_types/examples/input_types.png
ADDED
|
comfy/comfy_types/examples/required_hint.png
ADDED
|
comfy/comfy_types/node_typing.py
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Comfy-specific type hinting"""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
from typing import Literal, TypedDict, Optional
|
| 5 |
+
from typing_extensions import NotRequired
|
| 6 |
+
from abc import ABC, abstractmethod
|
| 7 |
+
from enum import Enum
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class StrEnum(str, Enum):
|
| 11 |
+
"""Base class for string enums. Python's StrEnum is not available until 3.11."""
|
| 12 |
+
|
| 13 |
+
def __str__(self) -> str:
|
| 14 |
+
return self.value
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class IO(StrEnum):
|
| 18 |
+
"""Node input/output data types.
|
| 19 |
+
|
| 20 |
+
Includes functionality for ``"*"`` (`ANY`) and ``"MULTI,TYPES"``.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
STRING = "STRING"
|
| 24 |
+
IMAGE = "IMAGE"
|
| 25 |
+
MASK = "MASK"
|
| 26 |
+
LATENT = "LATENT"
|
| 27 |
+
BOOLEAN = "BOOLEAN"
|
| 28 |
+
INT = "INT"
|
| 29 |
+
FLOAT = "FLOAT"
|
| 30 |
+
COMBO = "COMBO"
|
| 31 |
+
CONDITIONING = "CONDITIONING"
|
| 32 |
+
SAMPLER = "SAMPLER"
|
| 33 |
+
SIGMAS = "SIGMAS"
|
| 34 |
+
GUIDER = "GUIDER"
|
| 35 |
+
NOISE = "NOISE"
|
| 36 |
+
CLIP = "CLIP"
|
| 37 |
+
CONTROL_NET = "CONTROL_NET"
|
| 38 |
+
VAE = "VAE"
|
| 39 |
+
MODEL = "MODEL"
|
| 40 |
+
LORA_MODEL = "LORA_MODEL"
|
| 41 |
+
LOSS_MAP = "LOSS_MAP"
|
| 42 |
+
CLIP_VISION = "CLIP_VISION"
|
| 43 |
+
CLIP_VISION_OUTPUT = "CLIP_VISION_OUTPUT"
|
| 44 |
+
STYLE_MODEL = "STYLE_MODEL"
|
| 45 |
+
GLIGEN = "GLIGEN"
|
| 46 |
+
UPSCALE_MODEL = "UPSCALE_MODEL"
|
| 47 |
+
AUDIO = "AUDIO"
|
| 48 |
+
WEBCAM = "WEBCAM"
|
| 49 |
+
POINT = "POINT"
|
| 50 |
+
FACE_ANALYSIS = "FACE_ANALYSIS"
|
| 51 |
+
BBOX = "BBOX"
|
| 52 |
+
SEGS = "SEGS"
|
| 53 |
+
VIDEO = "VIDEO"
|
| 54 |
+
|
| 55 |
+
ANY = "*"
|
| 56 |
+
"""Always matches any type, but at a price.
|
| 57 |
+
|
| 58 |
+
Causes some functionality issues (e.g. reroutes, link types), and should be avoided whenever possible.
|
| 59 |
+
"""
|
| 60 |
+
NUMBER = "FLOAT,INT"
|
| 61 |
+
"""A float or an int - could be either"""
|
| 62 |
+
PRIMITIVE = "STRING,FLOAT,INT,BOOLEAN"
|
| 63 |
+
"""Could be any of: string, float, int, or bool"""
|
| 64 |
+
|
| 65 |
+
def __ne__(self, value: object) -> bool:
|
| 66 |
+
if self == "*" or value == "*":
|
| 67 |
+
return False
|
| 68 |
+
if not isinstance(value, str):
|
| 69 |
+
return True
|
| 70 |
+
a = frozenset(self.split(","))
|
| 71 |
+
b = frozenset(value.split(","))
|
| 72 |
+
return not (b.issubset(a) or a.issubset(b))
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class RemoteInputOptions(TypedDict):
|
| 76 |
+
route: str
|
| 77 |
+
"""The route to the remote source."""
|
| 78 |
+
refresh_button: bool
|
| 79 |
+
"""Specifies whether to show a refresh button in the UI below the widget."""
|
| 80 |
+
control_after_refresh: Literal["first", "last"]
|
| 81 |
+
"""Specifies the control after the refresh button is clicked. If "first", the first item will be automatically selected, and so on."""
|
| 82 |
+
timeout: int
|
| 83 |
+
"""The maximum amount of time to wait for a response from the remote source in milliseconds."""
|
| 84 |
+
max_retries: int
|
| 85 |
+
"""The maximum number of retries before aborting the request."""
|
| 86 |
+
refresh: int
|
| 87 |
+
"""The TTL of the remote input's value in milliseconds. Specifies the interval at which the remote input's value is refreshed."""
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class MultiSelectOptions(TypedDict):
|
| 91 |
+
placeholder: NotRequired[str]
|
| 92 |
+
"""The placeholder text to display in the multi-select widget when no items are selected."""
|
| 93 |
+
chip: NotRequired[bool]
|
| 94 |
+
"""Specifies whether to use chips instead of comma separated values for the multi-select widget."""
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class InputTypeOptions(TypedDict):
|
| 98 |
+
"""Provides type hinting for the return type of the INPUT_TYPES node function.
|
| 99 |
+
|
| 100 |
+
Due to IDE limitations with unions, for now all options are available for all types (e.g. `label_on` is hinted even when the type is not `IO.BOOLEAN`).
|
| 101 |
+
|
| 102 |
+
Comfy Docs: https://docs.comfy.org/custom-nodes/backend/datatypes
|
| 103 |
+
"""
|
| 104 |
+
|
| 105 |
+
default: NotRequired[bool | str | float | int | list | tuple]
|
| 106 |
+
"""The default value of the widget"""
|
| 107 |
+
defaultInput: NotRequired[bool]
|
| 108 |
+
"""@deprecated in v1.16 frontend. v1.16 frontend allows input socket and widget to co-exist.
|
| 109 |
+
- defaultInput on required inputs should be dropped.
|
| 110 |
+
- defaultInput on optional inputs should be replaced with forceInput.
|
| 111 |
+
Ref: https://github.com/Comfy-Org/ComfyUI_frontend/pull/3364
|
| 112 |
+
"""
|
| 113 |
+
forceInput: NotRequired[bool]
|
| 114 |
+
"""Forces the input to be an input slot rather than a widget even a widget is available for the input type."""
|
| 115 |
+
lazy: NotRequired[bool]
|
| 116 |
+
"""Declares that this input uses lazy evaluation"""
|
| 117 |
+
rawLink: NotRequired[bool]
|
| 118 |
+
"""When a link exists, rather than receiving the evaluated value, you will receive the link (i.e. `["nodeId", <outputIndex>]`). Designed for node expansion."""
|
| 119 |
+
tooltip: NotRequired[str]
|
| 120 |
+
"""Tooltip for the input (or widget), shown on pointer hover"""
|
| 121 |
+
socketless: NotRequired[bool]
|
| 122 |
+
"""All inputs (including widgets) have an input socket to connect links. When ``true``, if there is a widget for this input, no socket will be created.
|
| 123 |
+
Available from frontend v1.17.5
|
| 124 |
+
Ref: https://github.com/Comfy-Org/ComfyUI_frontend/pull/3548
|
| 125 |
+
"""
|
| 126 |
+
widgetType: NotRequired[str]
|
| 127 |
+
"""Specifies a type to be used for widget initialization if different from the input type.
|
| 128 |
+
Available from frontend v1.18.0
|
| 129 |
+
https://github.com/Comfy-Org/ComfyUI_frontend/pull/3550"""
|
| 130 |
+
# class InputTypeNumber(InputTypeOptions):
|
| 131 |
+
# default: float | int
|
| 132 |
+
min: NotRequired[float]
|
| 133 |
+
"""The minimum value of a number (``FLOAT`` | ``INT``)"""
|
| 134 |
+
max: NotRequired[float]
|
| 135 |
+
"""The maximum value of a number (``FLOAT`` | ``INT``)"""
|
| 136 |
+
step: NotRequired[float]
|
| 137 |
+
"""The amount to increment or decrement a widget by when stepping up/down (``FLOAT`` | ``INT``)"""
|
| 138 |
+
round: NotRequired[float]
|
| 139 |
+
"""Floats are rounded by this value (``FLOAT``)"""
|
| 140 |
+
# class InputTypeBoolean(InputTypeOptions):
|
| 141 |
+
# default: bool
|
| 142 |
+
label_on: NotRequired[str]
|
| 143 |
+
"""The label to use in the UI when the bool is True (``BOOLEAN``)"""
|
| 144 |
+
label_off: NotRequired[str]
|
| 145 |
+
"""The label to use in the UI when the bool is False (``BOOLEAN``)"""
|
| 146 |
+
# class InputTypeString(InputTypeOptions):
|
| 147 |
+
# default: str
|
| 148 |
+
multiline: NotRequired[bool]
|
| 149 |
+
"""Use a multiline text box (``STRING``)"""
|
| 150 |
+
placeholder: NotRequired[str]
|
| 151 |
+
"""Placeholder text to display in the UI when empty (``STRING``)"""
|
| 152 |
+
# Deprecated:
|
| 153 |
+
# defaultVal: str
|
| 154 |
+
dynamicPrompts: NotRequired[bool]
|
| 155 |
+
"""Causes the front-end to evaluate dynamic prompts (``STRING``)"""
|
| 156 |
+
# class InputTypeCombo(InputTypeOptions):
|
| 157 |
+
image_upload: NotRequired[bool]
|
| 158 |
+
"""Specifies whether the input should have an image upload button and image preview attached to it. Requires that the input's name is `image`."""
|
| 159 |
+
image_folder: NotRequired[Literal["input", "output", "temp"]]
|
| 160 |
+
"""Specifies which folder to get preview images from if the input has the ``image_upload`` flag.
|
| 161 |
+
"""
|
| 162 |
+
remote: NotRequired[RemoteInputOptions]
|
| 163 |
+
"""Specifies the configuration for a remote input.
|
| 164 |
+
Available after ComfyUI frontend v1.9.7
|
| 165 |
+
https://github.com/Comfy-Org/ComfyUI_frontend/pull/2422"""
|
| 166 |
+
control_after_generate: NotRequired[bool]
|
| 167 |
+
"""Specifies whether a control widget should be added to the input, adding options to automatically change the value after each prompt is queued. Currently only used for INT and COMBO types."""
|
| 168 |
+
options: NotRequired[list[str | int | float]]
|
| 169 |
+
"""COMBO type only. Specifies the selectable options for the combo widget.
|
| 170 |
+
Prefer:
|
| 171 |
+
["COMBO", {"options": ["Option 1", "Option 2", "Option 3"]}]
|
| 172 |
+
Over:
|
| 173 |
+
[["Option 1", "Option 2", "Option 3"]]
|
| 174 |
+
"""
|
| 175 |
+
multi_select: NotRequired[MultiSelectOptions]
|
| 176 |
+
"""COMBO type only. Specifies the configuration for a multi-select widget.
|
| 177 |
+
Available after ComfyUI frontend v1.13.4
|
| 178 |
+
https://github.com/Comfy-Org/ComfyUI_frontend/pull/2987"""
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
class HiddenInputTypeDict(TypedDict):
|
| 182 |
+
"""Provides type hinting for the hidden entry of node INPUT_TYPES."""
|
| 183 |
+
|
| 184 |
+
node_id: NotRequired[Literal["UNIQUE_ID"]]
|
| 185 |
+
"""UNIQUE_ID is the unique identifier of the node, and matches the id property of the node on the client side. It is commonly used in client-server communications (see messages)."""
|
| 186 |
+
unique_id: NotRequired[Literal["UNIQUE_ID"]]
|
| 187 |
+
"""UNIQUE_ID is the unique identifier of the node, and matches the id property of the node on the client side. It is commonly used in client-server communications (see messages)."""
|
| 188 |
+
prompt: NotRequired[Literal["PROMPT"]]
|
| 189 |
+
"""PROMPT is the complete prompt sent by the client to the server. See the prompt object for a full description."""
|
| 190 |
+
extra_pnginfo: NotRequired[Literal["EXTRA_PNGINFO"]]
|
| 191 |
+
"""EXTRA_PNGINFO is a dictionary that will be copied into the metadata of any .png files saved. Custom nodes can store additional information in this dictionary for saving (or as a way to communicate with a downstream node)."""
|
| 192 |
+
dynprompt: NotRequired[Literal["DYNPROMPT"]]
|
| 193 |
+
"""DYNPROMPT is an instance of comfy_execution.graph.DynamicPrompt. It differs from PROMPT in that it may mutate during the course of execution in response to Node Expansion."""
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
class InputTypeDict(TypedDict):
|
| 197 |
+
"""Provides type hinting for node INPUT_TYPES.
|
| 198 |
+
|
| 199 |
+
Comfy Docs: https://docs.comfy.org/custom-nodes/backend/more_on_inputs
|
| 200 |
+
"""
|
| 201 |
+
|
| 202 |
+
required: NotRequired[dict[str, tuple[IO, InputTypeOptions]]]
|
| 203 |
+
"""Describes all inputs that must be connected for the node to execute."""
|
| 204 |
+
optional: NotRequired[dict[str, tuple[IO, InputTypeOptions]]]
|
| 205 |
+
"""Describes inputs which do not need to be connected."""
|
| 206 |
+
hidden: NotRequired[HiddenInputTypeDict]
|
| 207 |
+
"""Offers advanced functionality and server-client communication.
|
| 208 |
+
|
| 209 |
+
Comfy Docs: https://docs.comfy.org/custom-nodes/backend/more_on_inputs#hidden-inputs
|
| 210 |
+
"""
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
class ComfyNodeABC(ABC):
|
| 214 |
+
"""Abstract base class for Comfy nodes. Includes the names and expected types of attributes.
|
| 215 |
+
|
| 216 |
+
Comfy Docs: https://docs.comfy.org/custom-nodes/backend/server_overview
|
| 217 |
+
"""
|
| 218 |
+
|
| 219 |
+
DESCRIPTION: str
|
| 220 |
+
"""Node description, shown as a tooltip when hovering over the node.
|
| 221 |
+
|
| 222 |
+
Usage::
|
| 223 |
+
|
| 224 |
+
# Explicitly define the description
|
| 225 |
+
DESCRIPTION = "Example description here."
|
| 226 |
+
|
| 227 |
+
# Use the docstring of the node class.
|
| 228 |
+
DESCRIPTION = cleandoc(__doc__)
|
| 229 |
+
"""
|
| 230 |
+
CATEGORY: str
|
| 231 |
+
"""The category of the node, as per the "Add Node" menu.
|
| 232 |
+
|
| 233 |
+
Comfy Docs: https://docs.comfy.org/custom-nodes/backend/server_overview#category
|
| 234 |
+
"""
|
| 235 |
+
EXPERIMENTAL: bool
|
| 236 |
+
"""Flags a node as experimental, informing users that it may change or not work as expected."""
|
| 237 |
+
DEPRECATED: bool
|
| 238 |
+
"""Flags a node as deprecated, indicating to users that they should find alternatives to this node."""
|
| 239 |
+
API_NODE: Optional[bool]
|
| 240 |
+
"""Flags a node as an API node. See: https://docs.comfy.org/tutorials/api-nodes/overview."""
|
| 241 |
+
|
| 242 |
+
@classmethod
|
| 243 |
+
@abstractmethod
|
| 244 |
+
def INPUT_TYPES(s) -> InputTypeDict:
|
| 245 |
+
"""Defines node inputs.
|
| 246 |
+
|
| 247 |
+
* Must include the ``required`` key, which describes all inputs that must be connected for the node to execute.
|
| 248 |
+
* The ``optional`` key can be added to describe inputs which do not need to be connected.
|
| 249 |
+
* The ``hidden`` key offers some advanced functionality. More info at: https://docs.comfy.org/custom-nodes/backend/more_on_inputs#hidden-inputs
|
| 250 |
+
|
| 251 |
+
Comfy Docs: https://docs.comfy.org/custom-nodes/backend/server_overview#input-types
|
| 252 |
+
"""
|
| 253 |
+
return {"required": {}}
|
| 254 |
+
|
| 255 |
+
OUTPUT_NODE: bool
|
| 256 |
+
"""Flags this node as an output node, causing any inputs it requires to be executed.
|
| 257 |
+
|
| 258 |
+
If a node is not connected to any output nodes, that node will not be executed. Usage::
|
| 259 |
+
|
| 260 |
+
OUTPUT_NODE = True
|
| 261 |
+
|
| 262 |
+
From the docs:
|
| 263 |
+
|
| 264 |
+
By default, a node is not considered an output. Set ``OUTPUT_NODE = True`` to specify that it is.
|
| 265 |
+
|
| 266 |
+
Comfy Docs: https://docs.comfy.org/custom-nodes/backend/server_overview#output-node
|
| 267 |
+
"""
|
| 268 |
+
INPUT_IS_LIST: bool
|
| 269 |
+
"""A flag indicating if this node implements the additional code necessary to deal with OUTPUT_IS_LIST nodes.
|
| 270 |
+
|
| 271 |
+
All inputs of ``type`` will become ``list[type]``, regardless of how many items are passed in. This also affects ``check_lazy_status``.
|
| 272 |
+
|
| 273 |
+
From the docs:
|
| 274 |
+
|
| 275 |
+
A node can also override the default input behaviour and receive the whole list in a single call. This is done by setting a class attribute `INPUT_IS_LIST` to ``True``.
|
| 276 |
+
|
| 277 |
+
Comfy Docs: https://docs.comfy.org/custom-nodes/backend/lists#list-processing
|
| 278 |
+
"""
|
| 279 |
+
OUTPUT_IS_LIST: tuple[bool, ...]
|
| 280 |
+
"""A tuple indicating which node outputs are lists, but will be connected to nodes that expect individual items.
|
| 281 |
+
|
| 282 |
+
Connected nodes that do not implement `INPUT_IS_LIST` will be executed once for every item in the list.
|
| 283 |
+
|
| 284 |
+
A ``tuple[bool]``, where the items match those in `RETURN_TYPES`::
|
| 285 |
+
|
| 286 |
+
RETURN_TYPES = (IO.INT, IO.INT, IO.STRING)
|
| 287 |
+
OUTPUT_IS_LIST = (True, True, False) # The string output will be handled normally
|
| 288 |
+
|
| 289 |
+
From the docs:
|
| 290 |
+
|
| 291 |
+
In order to tell Comfy that the list being returned should not be wrapped, but treated as a series of data for sequential processing,
|
| 292 |
+
the node should provide a class attribute `OUTPUT_IS_LIST`, which is a ``tuple[bool]``, of the same length as `RETURN_TYPES`,
|
| 293 |
+
specifying which outputs which should be so treated.
|
| 294 |
+
|
| 295 |
+
Comfy Docs: https://docs.comfy.org/custom-nodes/backend/lists#list-processing
|
| 296 |
+
"""
|
| 297 |
+
|
| 298 |
+
RETURN_TYPES: tuple[IO, ...]
|
| 299 |
+
"""A tuple representing the outputs of this node.
|
| 300 |
+
|
| 301 |
+
Usage::
|
| 302 |
+
|
| 303 |
+
RETURN_TYPES = (IO.INT, "INT", "CUSTOM_TYPE")
|
| 304 |
+
|
| 305 |
+
Comfy Docs: https://docs.comfy.org/custom-nodes/backend/server_overview#return-types
|
| 306 |
+
"""
|
| 307 |
+
RETURN_NAMES: tuple[str, ...]
|
| 308 |
+
"""The output slot names for each item in `RETURN_TYPES`, e.g. ``RETURN_NAMES = ("count", "filter_string")``
|
| 309 |
+
|
| 310 |
+
Comfy Docs: https://docs.comfy.org/custom-nodes/backend/server_overview#return-names
|
| 311 |
+
"""
|
| 312 |
+
OUTPUT_TOOLTIPS: tuple[str, ...]
|
| 313 |
+
"""A tuple of strings to use as tooltips for node outputs, one for each item in `RETURN_TYPES`."""
|
| 314 |
+
FUNCTION: str
|
| 315 |
+
"""The name of the function to execute as a literal string, e.g. `FUNCTION = "execute"`
|
| 316 |
+
|
| 317 |
+
Comfy Docs: https://docs.comfy.org/custom-nodes/backend/server_overview#function
|
| 318 |
+
"""
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
class CheckLazyMixin:
|
| 322 |
+
"""Provides a basic check_lazy_status implementation and type hinting for nodes that use lazy inputs."""
|
| 323 |
+
|
| 324 |
+
def check_lazy_status(self, **kwargs) -> list[str]:
|
| 325 |
+
"""Returns a list of input names that should be evaluated.
|
| 326 |
+
|
| 327 |
+
This basic mixin impl. requires all inputs.
|
| 328 |
+
|
| 329 |
+
:kwargs: All node inputs will be included here. If the input is ``None``, it should be assumed that it has not yet been evaluated. \
|
| 330 |
+
When using ``INPUT_IS_LIST = True``, unevaluated will instead be ``(None,)``.
|
| 331 |
+
|
| 332 |
+
Params should match the nodes execution ``FUNCTION`` (self, and all inputs by name).
|
| 333 |
+
Will be executed repeatedly until it returns an empty list, or all requested items were already evaluated (and sent as params).
|
| 334 |
+
|
| 335 |
+
Comfy Docs: https://docs.comfy.org/custom-nodes/backend/lazy_evaluation#defining-check-lazy-status
|
| 336 |
+
"""
|
| 337 |
+
|
| 338 |
+
need = [name for name in kwargs if kwargs[name] is None]
|
| 339 |
+
return need
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
class FileLocator(TypedDict):
|
| 343 |
+
"""Provides type hinting for the file location"""
|
| 344 |
+
|
| 345 |
+
filename: str
|
| 346 |
+
"""The filename of the file."""
|
| 347 |
+
subfolder: str
|
| 348 |
+
"""The subfolder of the file."""
|
| 349 |
+
type: Literal["input", "output", "temp"]
|
| 350 |
+
"""The root folder of the file."""
|
comfy/conds.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import math
|
| 3 |
+
import comfy.utils
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class CONDRegular:
|
| 7 |
+
def __init__(self, cond):
|
| 8 |
+
self.cond = cond
|
| 9 |
+
|
| 10 |
+
def _copy_with(self, cond):
|
| 11 |
+
return self.__class__(cond)
|
| 12 |
+
|
| 13 |
+
def process_cond(self, batch_size, device, **kwargs):
|
| 14 |
+
return self._copy_with(comfy.utils.repeat_to_batch_size(self.cond, batch_size).to(device))
|
| 15 |
+
|
| 16 |
+
def can_concat(self, other):
|
| 17 |
+
if self.cond.shape != other.cond.shape:
|
| 18 |
+
return False
|
| 19 |
+
return True
|
| 20 |
+
|
| 21 |
+
def concat(self, others):
|
| 22 |
+
conds = [self.cond]
|
| 23 |
+
for x in others:
|
| 24 |
+
conds.append(x.cond)
|
| 25 |
+
return torch.cat(conds)
|
| 26 |
+
|
| 27 |
+
def size(self):
|
| 28 |
+
return list(self.cond.size())
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class CONDNoiseShape(CONDRegular):
|
| 32 |
+
def process_cond(self, batch_size, device, area, **kwargs):
|
| 33 |
+
data = self.cond
|
| 34 |
+
if area is not None:
|
| 35 |
+
dims = len(area) // 2
|
| 36 |
+
for i in range(dims):
|
| 37 |
+
data = data.narrow(i + 2, area[i + dims], area[i])
|
| 38 |
+
|
| 39 |
+
return self._copy_with(comfy.utils.repeat_to_batch_size(data, batch_size).to(device))
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class CONDCrossAttn(CONDRegular):
|
| 43 |
+
def can_concat(self, other):
|
| 44 |
+
s1 = self.cond.shape
|
| 45 |
+
s2 = other.cond.shape
|
| 46 |
+
if s1 != s2:
|
| 47 |
+
if s1[0] != s2[0] or s1[2] != s2[2]: #these 2 cases should not happen
|
| 48 |
+
return False
|
| 49 |
+
|
| 50 |
+
mult_min = math.lcm(s1[1], s2[1])
|
| 51 |
+
diff = mult_min // min(s1[1], s2[1])
|
| 52 |
+
if diff > 4: #arbitrary limit on the padding because it's probably going to impact performance negatively if it's too much
|
| 53 |
+
return False
|
| 54 |
+
return True
|
| 55 |
+
|
| 56 |
+
def concat(self, others):
|
| 57 |
+
conds = [self.cond]
|
| 58 |
+
crossattn_max_len = self.cond.shape[1]
|
| 59 |
+
for x in others:
|
| 60 |
+
c = x.cond
|
| 61 |
+
crossattn_max_len = math.lcm(crossattn_max_len, c.shape[1])
|
| 62 |
+
conds.append(c)
|
| 63 |
+
|
| 64 |
+
out = []
|
| 65 |
+
for c in conds:
|
| 66 |
+
if c.shape[1] < crossattn_max_len:
|
| 67 |
+
c = c.repeat(1, crossattn_max_len // c.shape[1], 1) #padding with repeat doesn't change result
|
| 68 |
+
out.append(c)
|
| 69 |
+
return torch.cat(out)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class CONDConstant(CONDRegular):
|
| 73 |
+
def __init__(self, cond):
|
| 74 |
+
self.cond = cond
|
| 75 |
+
|
| 76 |
+
def process_cond(self, batch_size, device, **kwargs):
|
| 77 |
+
return self._copy_with(self.cond)
|
| 78 |
+
|
| 79 |
+
def can_concat(self, other):
|
| 80 |
+
if self.cond != other.cond:
|
| 81 |
+
return False
|
| 82 |
+
return True
|
| 83 |
+
|
| 84 |
+
def concat(self, others):
|
| 85 |
+
return self.cond
|
| 86 |
+
|
| 87 |
+
def size(self):
|
| 88 |
+
return [1]
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
class CONDList(CONDRegular):
|
| 92 |
+
def __init__(self, cond):
|
| 93 |
+
self.cond = cond
|
| 94 |
+
|
| 95 |
+
def process_cond(self, batch_size, device, **kwargs):
|
| 96 |
+
out = []
|
| 97 |
+
for c in self.cond:
|
| 98 |
+
out.append(comfy.utils.repeat_to_batch_size(c, batch_size).to(device))
|
| 99 |
+
|
| 100 |
+
return self._copy_with(out)
|
| 101 |
+
|
| 102 |
+
def can_concat(self, other):
|
| 103 |
+
if len(self.cond) != len(other.cond):
|
| 104 |
+
return False
|
| 105 |
+
for i in range(len(self.cond)):
|
| 106 |
+
if self.cond[i].shape != other.cond[i].shape:
|
| 107 |
+
return False
|
| 108 |
+
|
| 109 |
+
return True
|
| 110 |
+
|
| 111 |
+
def concat(self, others):
|
| 112 |
+
out = []
|
| 113 |
+
for i in range(len(self.cond)):
|
| 114 |
+
o = [self.cond[i]]
|
| 115 |
+
for x in others:
|
| 116 |
+
o.append(x.cond[i])
|
| 117 |
+
out.append(torch.cat(o))
|
| 118 |
+
|
| 119 |
+
return out
|
| 120 |
+
|
| 121 |
+
def size(self): # hackish implementation to make the mem estimation work
|
| 122 |
+
o = 0
|
| 123 |
+
c = 1
|
| 124 |
+
for c in self.cond:
|
| 125 |
+
size = c.size()
|
| 126 |
+
o += math.prod(size)
|
| 127 |
+
if len(size) > 1:
|
| 128 |
+
c = size[1]
|
| 129 |
+
|
| 130 |
+
return [1, c, o // c]
|
comfy/controlnet.py
ADDED
|
@@ -0,0 +1,858 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This file is part of ComfyUI.
|
| 3 |
+
Copyright (C) 2024 Comfy
|
| 4 |
+
|
| 5 |
+
This program is free software: you can redistribute it and/or modify
|
| 6 |
+
it under the terms of the GNU General Public License as published by
|
| 7 |
+
the Free Software Foundation, either version 3 of the License, or
|
| 8 |
+
(at your option) any later version.
|
| 9 |
+
|
| 10 |
+
This program is distributed in the hope that it will be useful,
|
| 11 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 12 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 13 |
+
GNU General Public License for more details.
|
| 14 |
+
|
| 15 |
+
You should have received a copy of the GNU General Public License
|
| 16 |
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
from enum import Enum
|
| 22 |
+
import math
|
| 23 |
+
import os
|
| 24 |
+
import logging
|
| 25 |
+
import comfy.utils
|
| 26 |
+
import comfy.model_management
|
| 27 |
+
import comfy.model_detection
|
| 28 |
+
import comfy.model_patcher
|
| 29 |
+
import comfy.ops
|
| 30 |
+
import comfy.latent_formats
|
| 31 |
+
|
| 32 |
+
import comfy.cldm.cldm
|
| 33 |
+
import comfy.t2i_adapter.adapter
|
| 34 |
+
import comfy.ldm.cascade.controlnet
|
| 35 |
+
import comfy.cldm.mmdit
|
| 36 |
+
import comfy.ldm.hydit.controlnet
|
| 37 |
+
import comfy.ldm.flux.controlnet
|
| 38 |
+
import comfy.cldm.dit_embedder
|
| 39 |
+
from typing import TYPE_CHECKING
|
| 40 |
+
if TYPE_CHECKING:
|
| 41 |
+
from comfy.hooks import HookGroup
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def broadcast_image_to(tensor, target_batch_size, batched_number):
|
| 45 |
+
current_batch_size = tensor.shape[0]
|
| 46 |
+
#print(current_batch_size, target_batch_size)
|
| 47 |
+
if current_batch_size == 1:
|
| 48 |
+
return tensor
|
| 49 |
+
|
| 50 |
+
per_batch = target_batch_size // batched_number
|
| 51 |
+
tensor = tensor[:per_batch]
|
| 52 |
+
|
| 53 |
+
if per_batch > tensor.shape[0]:
|
| 54 |
+
tensor = torch.cat([tensor] * (per_batch // tensor.shape[0]) + [tensor[:(per_batch % tensor.shape[0])]], dim=0)
|
| 55 |
+
|
| 56 |
+
current_batch_size = tensor.shape[0]
|
| 57 |
+
if current_batch_size == target_batch_size:
|
| 58 |
+
return tensor
|
| 59 |
+
else:
|
| 60 |
+
return torch.cat([tensor] * batched_number, dim=0)
|
| 61 |
+
|
| 62 |
+
class StrengthType(Enum):
|
| 63 |
+
CONSTANT = 1
|
| 64 |
+
LINEAR_UP = 2
|
| 65 |
+
|
| 66 |
+
class ControlBase:
|
| 67 |
+
def __init__(self):
|
| 68 |
+
self.cond_hint_original = None
|
| 69 |
+
self.cond_hint = None
|
| 70 |
+
self.strength = 1.0
|
| 71 |
+
self.timestep_percent_range = (0.0, 1.0)
|
| 72 |
+
self.latent_format = None
|
| 73 |
+
self.vae = None
|
| 74 |
+
self.global_average_pooling = False
|
| 75 |
+
self.timestep_range = None
|
| 76 |
+
self.compression_ratio = 8
|
| 77 |
+
self.upscale_algorithm = 'nearest-exact'
|
| 78 |
+
self.extra_args = {}
|
| 79 |
+
self.previous_controlnet = None
|
| 80 |
+
self.extra_conds = []
|
| 81 |
+
self.strength_type = StrengthType.CONSTANT
|
| 82 |
+
self.concat_mask = False
|
| 83 |
+
self.extra_concat_orig = []
|
| 84 |
+
self.extra_concat = None
|
| 85 |
+
self.extra_hooks: HookGroup = None
|
| 86 |
+
self.preprocess_image = lambda a: a
|
| 87 |
+
|
| 88 |
+
def set_cond_hint(self, cond_hint, strength=1.0, timestep_percent_range=(0.0, 1.0), vae=None, extra_concat=[]):
|
| 89 |
+
self.cond_hint_original = cond_hint
|
| 90 |
+
self.strength = strength
|
| 91 |
+
self.timestep_percent_range = timestep_percent_range
|
| 92 |
+
if self.latent_format is not None:
|
| 93 |
+
if vae is None:
|
| 94 |
+
logging.warning("WARNING: no VAE provided to the controlnet apply node when this controlnet requires one.")
|
| 95 |
+
self.vae = vae
|
| 96 |
+
self.extra_concat_orig = extra_concat.copy()
|
| 97 |
+
if self.concat_mask and len(self.extra_concat_orig) == 0:
|
| 98 |
+
self.extra_concat_orig.append(torch.tensor([[[[1.0]]]]))
|
| 99 |
+
return self
|
| 100 |
+
|
| 101 |
+
def pre_run(self, model, percent_to_timestep_function):
|
| 102 |
+
self.timestep_range = (percent_to_timestep_function(self.timestep_percent_range[0]), percent_to_timestep_function(self.timestep_percent_range[1]))
|
| 103 |
+
if self.previous_controlnet is not None:
|
| 104 |
+
self.previous_controlnet.pre_run(model, percent_to_timestep_function)
|
| 105 |
+
|
| 106 |
+
def set_previous_controlnet(self, controlnet):
|
| 107 |
+
self.previous_controlnet = controlnet
|
| 108 |
+
return self
|
| 109 |
+
|
| 110 |
+
def cleanup(self):
|
| 111 |
+
if self.previous_controlnet is not None:
|
| 112 |
+
self.previous_controlnet.cleanup()
|
| 113 |
+
|
| 114 |
+
self.cond_hint = None
|
| 115 |
+
self.extra_concat = None
|
| 116 |
+
self.timestep_range = None
|
| 117 |
+
|
| 118 |
+
def get_models(self):
|
| 119 |
+
out = []
|
| 120 |
+
if self.previous_controlnet is not None:
|
| 121 |
+
out += self.previous_controlnet.get_models()
|
| 122 |
+
return out
|
| 123 |
+
|
| 124 |
+
def get_extra_hooks(self):
|
| 125 |
+
out = []
|
| 126 |
+
if self.extra_hooks is not None:
|
| 127 |
+
out.append(self.extra_hooks)
|
| 128 |
+
if self.previous_controlnet is not None:
|
| 129 |
+
out += self.previous_controlnet.get_extra_hooks()
|
| 130 |
+
return out
|
| 131 |
+
|
| 132 |
+
def copy_to(self, c):
|
| 133 |
+
c.cond_hint_original = self.cond_hint_original
|
| 134 |
+
c.strength = self.strength
|
| 135 |
+
c.timestep_percent_range = self.timestep_percent_range
|
| 136 |
+
c.global_average_pooling = self.global_average_pooling
|
| 137 |
+
c.compression_ratio = self.compression_ratio
|
| 138 |
+
c.upscale_algorithm = self.upscale_algorithm
|
| 139 |
+
c.latent_format = self.latent_format
|
| 140 |
+
c.extra_args = self.extra_args.copy()
|
| 141 |
+
c.vae = self.vae
|
| 142 |
+
c.extra_conds = self.extra_conds.copy()
|
| 143 |
+
c.strength_type = self.strength_type
|
| 144 |
+
c.concat_mask = self.concat_mask
|
| 145 |
+
c.extra_concat_orig = self.extra_concat_orig.copy()
|
| 146 |
+
c.extra_hooks = self.extra_hooks.clone() if self.extra_hooks else None
|
| 147 |
+
c.preprocess_image = self.preprocess_image
|
| 148 |
+
|
| 149 |
+
def inference_memory_requirements(self, dtype):
|
| 150 |
+
if self.previous_controlnet is not None:
|
| 151 |
+
return self.previous_controlnet.inference_memory_requirements(dtype)
|
| 152 |
+
return 0
|
| 153 |
+
|
| 154 |
+
def control_merge(self, control, control_prev, output_dtype):
|
| 155 |
+
out = {'input':[], 'middle':[], 'output': []}
|
| 156 |
+
|
| 157 |
+
for key in control:
|
| 158 |
+
control_output = control[key]
|
| 159 |
+
applied_to = set()
|
| 160 |
+
for i in range(len(control_output)):
|
| 161 |
+
x = control_output[i]
|
| 162 |
+
if x is not None:
|
| 163 |
+
if self.global_average_pooling:
|
| 164 |
+
x = torch.mean(x, dim=(2, 3), keepdim=True).repeat(1, 1, x.shape[2], x.shape[3])
|
| 165 |
+
|
| 166 |
+
if x not in applied_to: #memory saving strategy, allow shared tensors and only apply strength to shared tensors once
|
| 167 |
+
applied_to.add(x)
|
| 168 |
+
if self.strength_type == StrengthType.CONSTANT:
|
| 169 |
+
x *= self.strength
|
| 170 |
+
elif self.strength_type == StrengthType.LINEAR_UP:
|
| 171 |
+
x *= (self.strength ** float(len(control_output) - i))
|
| 172 |
+
|
| 173 |
+
if output_dtype is not None and x.dtype != output_dtype:
|
| 174 |
+
x = x.to(output_dtype)
|
| 175 |
+
|
| 176 |
+
out[key].append(x)
|
| 177 |
+
|
| 178 |
+
if control_prev is not None:
|
| 179 |
+
for x in ['input', 'middle', 'output']:
|
| 180 |
+
o = out[x]
|
| 181 |
+
for i in range(len(control_prev[x])):
|
| 182 |
+
prev_val = control_prev[x][i]
|
| 183 |
+
if i >= len(o):
|
| 184 |
+
o.append(prev_val)
|
| 185 |
+
elif prev_val is not None:
|
| 186 |
+
if o[i] is None:
|
| 187 |
+
o[i] = prev_val
|
| 188 |
+
else:
|
| 189 |
+
if o[i].shape[0] < prev_val.shape[0]:
|
| 190 |
+
o[i] = prev_val + o[i]
|
| 191 |
+
else:
|
| 192 |
+
o[i] = prev_val + o[i] #TODO: change back to inplace add if shared tensors stop being an issue
|
| 193 |
+
return out
|
| 194 |
+
|
| 195 |
+
def set_extra_arg(self, argument, value=None):
|
| 196 |
+
self.extra_args[argument] = value
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
class ControlNet(ControlBase):
|
| 200 |
+
def __init__(self, control_model=None, global_average_pooling=False, compression_ratio=8, latent_format=None, load_device=None, manual_cast_dtype=None, extra_conds=["y"], strength_type=StrengthType.CONSTANT, concat_mask=False, preprocess_image=lambda a: a):
|
| 201 |
+
super().__init__()
|
| 202 |
+
self.control_model = control_model
|
| 203 |
+
self.load_device = load_device
|
| 204 |
+
if control_model is not None:
|
| 205 |
+
self.control_model_wrapped = comfy.model_patcher.ModelPatcher(self.control_model, load_device=load_device, offload_device=comfy.model_management.unet_offload_device())
|
| 206 |
+
|
| 207 |
+
self.compression_ratio = compression_ratio
|
| 208 |
+
self.global_average_pooling = global_average_pooling
|
| 209 |
+
self.model_sampling_current = None
|
| 210 |
+
self.manual_cast_dtype = manual_cast_dtype
|
| 211 |
+
self.latent_format = latent_format
|
| 212 |
+
self.extra_conds += extra_conds
|
| 213 |
+
self.strength_type = strength_type
|
| 214 |
+
self.concat_mask = concat_mask
|
| 215 |
+
self.preprocess_image = preprocess_image
|
| 216 |
+
|
| 217 |
+
def get_control(self, x_noisy, t, cond, batched_number, transformer_options):
|
| 218 |
+
control_prev = None
|
| 219 |
+
if self.previous_controlnet is not None:
|
| 220 |
+
control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number, transformer_options)
|
| 221 |
+
|
| 222 |
+
if self.timestep_range is not None:
|
| 223 |
+
if t[0] > self.timestep_range[0] or t[0] < self.timestep_range[1]:
|
| 224 |
+
if control_prev is not None:
|
| 225 |
+
return control_prev
|
| 226 |
+
else:
|
| 227 |
+
return None
|
| 228 |
+
|
| 229 |
+
dtype = self.control_model.dtype
|
| 230 |
+
if self.manual_cast_dtype is not None:
|
| 231 |
+
dtype = self.manual_cast_dtype
|
| 232 |
+
|
| 233 |
+
if self.cond_hint is None or x_noisy.shape[2] * self.compression_ratio != self.cond_hint.shape[2] or x_noisy.shape[3] * self.compression_ratio != self.cond_hint.shape[3]:
|
| 234 |
+
if self.cond_hint is not None:
|
| 235 |
+
del self.cond_hint
|
| 236 |
+
self.cond_hint = None
|
| 237 |
+
compression_ratio = self.compression_ratio
|
| 238 |
+
if self.vae is not None:
|
| 239 |
+
compression_ratio *= self.vae.downscale_ratio
|
| 240 |
+
else:
|
| 241 |
+
if self.latent_format is not None:
|
| 242 |
+
raise ValueError("This Controlnet needs a VAE but none was provided, please use a ControlNetApply node with a VAE input and connect it.")
|
| 243 |
+
self.cond_hint = comfy.utils.common_upscale(self.cond_hint_original, x_noisy.shape[3] * compression_ratio, x_noisy.shape[2] * compression_ratio, self.upscale_algorithm, "center")
|
| 244 |
+
self.cond_hint = self.preprocess_image(self.cond_hint)
|
| 245 |
+
if self.vae is not None:
|
| 246 |
+
loaded_models = comfy.model_management.loaded_models(only_currently_used=True)
|
| 247 |
+
self.cond_hint = self.vae.encode(self.cond_hint.movedim(1, -1))
|
| 248 |
+
comfy.model_management.load_models_gpu(loaded_models)
|
| 249 |
+
if self.latent_format is not None:
|
| 250 |
+
self.cond_hint = self.latent_format.process_in(self.cond_hint)
|
| 251 |
+
if len(self.extra_concat_orig) > 0:
|
| 252 |
+
to_concat = []
|
| 253 |
+
for c in self.extra_concat_orig:
|
| 254 |
+
c = c.to(self.cond_hint.device)
|
| 255 |
+
c = comfy.utils.common_upscale(c, self.cond_hint.shape[3], self.cond_hint.shape[2], self.upscale_algorithm, "center")
|
| 256 |
+
to_concat.append(comfy.utils.repeat_to_batch_size(c, self.cond_hint.shape[0]))
|
| 257 |
+
self.cond_hint = torch.cat([self.cond_hint] + to_concat, dim=1)
|
| 258 |
+
|
| 259 |
+
self.cond_hint = self.cond_hint.to(device=x_noisy.device, dtype=dtype)
|
| 260 |
+
if x_noisy.shape[0] != self.cond_hint.shape[0]:
|
| 261 |
+
self.cond_hint = broadcast_image_to(self.cond_hint, x_noisy.shape[0], batched_number)
|
| 262 |
+
|
| 263 |
+
context = cond.get('crossattn_controlnet', cond['c_crossattn'])
|
| 264 |
+
extra = self.extra_args.copy()
|
| 265 |
+
for c in self.extra_conds:
|
| 266 |
+
temp = cond.get(c, None)
|
| 267 |
+
if temp is not None:
|
| 268 |
+
extra[c] = temp.to(dtype)
|
| 269 |
+
|
| 270 |
+
timestep = self.model_sampling_current.timestep(t)
|
| 271 |
+
x_noisy = self.model_sampling_current.calculate_input(t, x_noisy)
|
| 272 |
+
|
| 273 |
+
control = self.control_model(x=x_noisy.to(dtype), hint=self.cond_hint, timesteps=timestep.to(dtype), context=context.to(dtype), **extra)
|
| 274 |
+
return self.control_merge(control, control_prev, output_dtype=None)
|
| 275 |
+
|
| 276 |
+
def copy(self):
|
| 277 |
+
c = ControlNet(None, global_average_pooling=self.global_average_pooling, load_device=self.load_device, manual_cast_dtype=self.manual_cast_dtype)
|
| 278 |
+
c.control_model = self.control_model
|
| 279 |
+
c.control_model_wrapped = self.control_model_wrapped
|
| 280 |
+
self.copy_to(c)
|
| 281 |
+
return c
|
| 282 |
+
|
| 283 |
+
def get_models(self):
|
| 284 |
+
out = super().get_models()
|
| 285 |
+
out.append(self.control_model_wrapped)
|
| 286 |
+
return out
|
| 287 |
+
|
| 288 |
+
def pre_run(self, model, percent_to_timestep_function):
|
| 289 |
+
super().pre_run(model, percent_to_timestep_function)
|
| 290 |
+
self.model_sampling_current = model.model_sampling
|
| 291 |
+
|
| 292 |
+
def cleanup(self):
|
| 293 |
+
self.model_sampling_current = None
|
| 294 |
+
super().cleanup()
|
| 295 |
+
|
| 296 |
+
class ControlLoraOps:
|
| 297 |
+
class Linear(torch.nn.Module, comfy.ops.CastWeightBiasOp):
|
| 298 |
+
def __init__(self, in_features: int, out_features: int, bias: bool = True,
|
| 299 |
+
device=None, dtype=None) -> None:
|
| 300 |
+
super().__init__()
|
| 301 |
+
self.in_features = in_features
|
| 302 |
+
self.out_features = out_features
|
| 303 |
+
self.weight = None
|
| 304 |
+
self.up = None
|
| 305 |
+
self.down = None
|
| 306 |
+
self.bias = None
|
| 307 |
+
|
| 308 |
+
def forward(self, input):
|
| 309 |
+
weight, bias = comfy.ops.cast_bias_weight(self, input)
|
| 310 |
+
if self.up is not None:
|
| 311 |
+
return torch.nn.functional.linear(input, weight + (torch.mm(self.up.flatten(start_dim=1), self.down.flatten(start_dim=1))).reshape(self.weight.shape).type(input.dtype), bias)
|
| 312 |
+
else:
|
| 313 |
+
return torch.nn.functional.linear(input, weight, bias)
|
| 314 |
+
|
| 315 |
+
class Conv2d(torch.nn.Module, comfy.ops.CastWeightBiasOp):
|
| 316 |
+
def __init__(
|
| 317 |
+
self,
|
| 318 |
+
in_channels,
|
| 319 |
+
out_channels,
|
| 320 |
+
kernel_size,
|
| 321 |
+
stride=1,
|
| 322 |
+
padding=0,
|
| 323 |
+
dilation=1,
|
| 324 |
+
groups=1,
|
| 325 |
+
bias=True,
|
| 326 |
+
padding_mode='zeros',
|
| 327 |
+
device=None,
|
| 328 |
+
dtype=None
|
| 329 |
+
):
|
| 330 |
+
super().__init__()
|
| 331 |
+
self.in_channels = in_channels
|
| 332 |
+
self.out_channels = out_channels
|
| 333 |
+
self.kernel_size = kernel_size
|
| 334 |
+
self.stride = stride
|
| 335 |
+
self.padding = padding
|
| 336 |
+
self.dilation = dilation
|
| 337 |
+
self.transposed = False
|
| 338 |
+
self.output_padding = 0
|
| 339 |
+
self.groups = groups
|
| 340 |
+
self.padding_mode = padding_mode
|
| 341 |
+
|
| 342 |
+
self.weight = None
|
| 343 |
+
self.bias = None
|
| 344 |
+
self.up = None
|
| 345 |
+
self.down = None
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def forward(self, input):
|
| 349 |
+
weight, bias = comfy.ops.cast_bias_weight(self, input)
|
| 350 |
+
if self.up is not None:
|
| 351 |
+
return torch.nn.functional.conv2d(input, weight + (torch.mm(self.up.flatten(start_dim=1), self.down.flatten(start_dim=1))).reshape(self.weight.shape).type(input.dtype), bias, self.stride, self.padding, self.dilation, self.groups)
|
| 352 |
+
else:
|
| 353 |
+
return torch.nn.functional.conv2d(input, weight, bias, self.stride, self.padding, self.dilation, self.groups)
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
class ControlLora(ControlNet):
|
| 357 |
+
def __init__(self, control_weights, global_average_pooling=False, model_options={}): #TODO? model_options
|
| 358 |
+
ControlBase.__init__(self)
|
| 359 |
+
self.control_weights = control_weights
|
| 360 |
+
self.global_average_pooling = global_average_pooling
|
| 361 |
+
self.extra_conds += ["y"]
|
| 362 |
+
|
| 363 |
+
def pre_run(self, model, percent_to_timestep_function):
|
| 364 |
+
super().pre_run(model, percent_to_timestep_function)
|
| 365 |
+
controlnet_config = model.model_config.unet_config.copy()
|
| 366 |
+
controlnet_config.pop("out_channels")
|
| 367 |
+
controlnet_config["hint_channels"] = self.control_weights["input_hint_block.0.weight"].shape[1]
|
| 368 |
+
self.manual_cast_dtype = model.manual_cast_dtype
|
| 369 |
+
dtype = model.get_dtype()
|
| 370 |
+
if self.manual_cast_dtype is None:
|
| 371 |
+
class control_lora_ops(ControlLoraOps, comfy.ops.disable_weight_init):
|
| 372 |
+
pass
|
| 373 |
+
else:
|
| 374 |
+
class control_lora_ops(ControlLoraOps, comfy.ops.manual_cast):
|
| 375 |
+
pass
|
| 376 |
+
dtype = self.manual_cast_dtype
|
| 377 |
+
|
| 378 |
+
controlnet_config["operations"] = control_lora_ops
|
| 379 |
+
controlnet_config["dtype"] = dtype
|
| 380 |
+
self.control_model = comfy.cldm.cldm.ControlNet(**controlnet_config)
|
| 381 |
+
self.control_model.to(comfy.model_management.get_torch_device())
|
| 382 |
+
diffusion_model = model.diffusion_model
|
| 383 |
+
sd = diffusion_model.state_dict()
|
| 384 |
+
|
| 385 |
+
for k in sd:
|
| 386 |
+
weight = sd[k]
|
| 387 |
+
try:
|
| 388 |
+
comfy.utils.set_attr_param(self.control_model, k, weight)
|
| 389 |
+
except:
|
| 390 |
+
pass
|
| 391 |
+
|
| 392 |
+
for k in self.control_weights:
|
| 393 |
+
if (k not in {"lora_controlnet"}):
|
| 394 |
+
if (k.endswith(".up") or k.endswith(".down") or k.endswith(".weight") or k.endswith(".bias")) and ("__" not in k):
|
| 395 |
+
comfy.utils.set_attr_param(self.control_model, k, self.control_weights[k].to(dtype).to(comfy.model_management.get_torch_device()))
|
| 396 |
+
|
| 397 |
+
def copy(self):
|
| 398 |
+
c = ControlLora(self.control_weights, global_average_pooling=self.global_average_pooling)
|
| 399 |
+
self.copy_to(c)
|
| 400 |
+
return c
|
| 401 |
+
|
| 402 |
+
def cleanup(self):
|
| 403 |
+
del self.control_model
|
| 404 |
+
self.control_model = None
|
| 405 |
+
super().cleanup()
|
| 406 |
+
|
| 407 |
+
def get_models(self):
|
| 408 |
+
out = ControlBase.get_models(self)
|
| 409 |
+
return out
|
| 410 |
+
|
| 411 |
+
def inference_memory_requirements(self, dtype):
|
| 412 |
+
return comfy.utils.calculate_parameters(self.control_weights) * comfy.model_management.dtype_size(dtype) + ControlBase.inference_memory_requirements(self, dtype)
|
| 413 |
+
|
| 414 |
+
def controlnet_config(sd, model_options={}):
|
| 415 |
+
model_config = comfy.model_detection.model_config_from_unet(sd, "", True)
|
| 416 |
+
|
| 417 |
+
unet_dtype = model_options.get("dtype", None)
|
| 418 |
+
if unet_dtype is None:
|
| 419 |
+
weight_dtype = comfy.utils.weight_dtype(sd)
|
| 420 |
+
|
| 421 |
+
supported_inference_dtypes = list(model_config.supported_inference_dtypes)
|
| 422 |
+
unet_dtype = comfy.model_management.unet_dtype(model_params=-1, supported_dtypes=supported_inference_dtypes, weight_dtype=weight_dtype)
|
| 423 |
+
|
| 424 |
+
load_device = comfy.model_management.get_torch_device()
|
| 425 |
+
manual_cast_dtype = comfy.model_management.unet_manual_cast(unet_dtype, load_device)
|
| 426 |
+
|
| 427 |
+
operations = model_options.get("custom_operations", None)
|
| 428 |
+
if operations is None:
|
| 429 |
+
operations = comfy.ops.pick_operations(unet_dtype, manual_cast_dtype, disable_fast_fp8=True)
|
| 430 |
+
|
| 431 |
+
offload_device = comfy.model_management.unet_offload_device()
|
| 432 |
+
return model_config, operations, load_device, unet_dtype, manual_cast_dtype, offload_device
|
| 433 |
+
|
| 434 |
+
def controlnet_load_state_dict(control_model, sd):
|
| 435 |
+
missing, unexpected = control_model.load_state_dict(sd, strict=False)
|
| 436 |
+
|
| 437 |
+
if len(missing) > 0:
|
| 438 |
+
logging.warning("missing controlnet keys: {}".format(missing))
|
| 439 |
+
|
| 440 |
+
if len(unexpected) > 0:
|
| 441 |
+
logging.debug("unexpected controlnet keys: {}".format(unexpected))
|
| 442 |
+
return control_model
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
def load_controlnet_mmdit(sd, model_options={}):
|
| 446 |
+
new_sd = comfy.model_detection.convert_diffusers_mmdit(sd, "")
|
| 447 |
+
model_config, operations, load_device, unet_dtype, manual_cast_dtype, offload_device = controlnet_config(new_sd, model_options=model_options)
|
| 448 |
+
num_blocks = comfy.model_detection.count_blocks(new_sd, 'joint_blocks.{}.')
|
| 449 |
+
for k in sd:
|
| 450 |
+
new_sd[k] = sd[k]
|
| 451 |
+
|
| 452 |
+
concat_mask = False
|
| 453 |
+
control_latent_channels = new_sd.get("pos_embed_input.proj.weight").shape[1]
|
| 454 |
+
if control_latent_channels == 17: #inpaint controlnet
|
| 455 |
+
concat_mask = True
|
| 456 |
+
|
| 457 |
+
control_model = comfy.cldm.mmdit.ControlNet(num_blocks=num_blocks, control_latent_channels=control_latent_channels, operations=operations, device=offload_device, dtype=unet_dtype, **model_config.unet_config)
|
| 458 |
+
control_model = controlnet_load_state_dict(control_model, new_sd)
|
| 459 |
+
|
| 460 |
+
latent_format = comfy.latent_formats.SD3()
|
| 461 |
+
latent_format.shift_factor = 0 #SD3 controlnet weirdness
|
| 462 |
+
control = ControlNet(control_model, compression_ratio=1, latent_format=latent_format, concat_mask=concat_mask, load_device=load_device, manual_cast_dtype=manual_cast_dtype)
|
| 463 |
+
return control
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
class ControlNetSD35(ControlNet):
|
| 467 |
+
def pre_run(self, model, percent_to_timestep_function):
|
| 468 |
+
if self.control_model.double_y_emb:
|
| 469 |
+
missing, unexpected = self.control_model.orig_y_embedder.load_state_dict(model.diffusion_model.y_embedder.state_dict(), strict=False)
|
| 470 |
+
else:
|
| 471 |
+
missing, unexpected = self.control_model.x_embedder.load_state_dict(model.diffusion_model.x_embedder.state_dict(), strict=False)
|
| 472 |
+
super().pre_run(model, percent_to_timestep_function)
|
| 473 |
+
|
| 474 |
+
def copy(self):
|
| 475 |
+
c = ControlNetSD35(None, global_average_pooling=self.global_average_pooling, load_device=self.load_device, manual_cast_dtype=self.manual_cast_dtype)
|
| 476 |
+
c.control_model = self.control_model
|
| 477 |
+
c.control_model_wrapped = self.control_model_wrapped
|
| 478 |
+
self.copy_to(c)
|
| 479 |
+
return c
|
| 480 |
+
|
| 481 |
+
def load_controlnet_sd35(sd, model_options={}):
|
| 482 |
+
control_type = -1
|
| 483 |
+
if "control_type" in sd:
|
| 484 |
+
control_type = round(sd.pop("control_type").item())
|
| 485 |
+
|
| 486 |
+
# blur_cnet = control_type == 0
|
| 487 |
+
canny_cnet = control_type == 1
|
| 488 |
+
depth_cnet = control_type == 2
|
| 489 |
+
|
| 490 |
+
new_sd = {}
|
| 491 |
+
for k in comfy.utils.MMDIT_MAP_BASIC:
|
| 492 |
+
if k[1] in sd:
|
| 493 |
+
new_sd[k[0]] = sd.pop(k[1])
|
| 494 |
+
for k in sd:
|
| 495 |
+
new_sd[k] = sd[k]
|
| 496 |
+
sd = new_sd
|
| 497 |
+
|
| 498 |
+
y_emb_shape = sd["y_embedder.mlp.0.weight"].shape
|
| 499 |
+
depth = y_emb_shape[0] // 64
|
| 500 |
+
hidden_size = 64 * depth
|
| 501 |
+
num_heads = depth
|
| 502 |
+
head_dim = hidden_size // num_heads
|
| 503 |
+
num_blocks = comfy.model_detection.count_blocks(new_sd, 'transformer_blocks.{}.')
|
| 504 |
+
|
| 505 |
+
load_device = comfy.model_management.get_torch_device()
|
| 506 |
+
offload_device = comfy.model_management.unet_offload_device()
|
| 507 |
+
unet_dtype = comfy.model_management.unet_dtype(model_params=-1)
|
| 508 |
+
|
| 509 |
+
manual_cast_dtype = comfy.model_management.unet_manual_cast(unet_dtype, load_device)
|
| 510 |
+
|
| 511 |
+
operations = model_options.get("custom_operations", None)
|
| 512 |
+
if operations is None:
|
| 513 |
+
operations = comfy.ops.pick_operations(unet_dtype, manual_cast_dtype, disable_fast_fp8=True)
|
| 514 |
+
|
| 515 |
+
control_model = comfy.cldm.dit_embedder.ControlNetEmbedder(img_size=None,
|
| 516 |
+
patch_size=2,
|
| 517 |
+
in_chans=16,
|
| 518 |
+
num_layers=num_blocks,
|
| 519 |
+
main_model_double=depth,
|
| 520 |
+
double_y_emb=y_emb_shape[0] == y_emb_shape[1],
|
| 521 |
+
attention_head_dim=head_dim,
|
| 522 |
+
num_attention_heads=num_heads,
|
| 523 |
+
adm_in_channels=2048,
|
| 524 |
+
device=offload_device,
|
| 525 |
+
dtype=unet_dtype,
|
| 526 |
+
operations=operations)
|
| 527 |
+
|
| 528 |
+
control_model = controlnet_load_state_dict(control_model, sd)
|
| 529 |
+
|
| 530 |
+
latent_format = comfy.latent_formats.SD3()
|
| 531 |
+
preprocess_image = lambda a: a
|
| 532 |
+
if canny_cnet:
|
| 533 |
+
preprocess_image = lambda a: (a * 255 * 0.5 + 0.5)
|
| 534 |
+
elif depth_cnet:
|
| 535 |
+
preprocess_image = lambda a: 1.0 - a
|
| 536 |
+
|
| 537 |
+
control = ControlNetSD35(control_model, compression_ratio=1, latent_format=latent_format, load_device=load_device, manual_cast_dtype=manual_cast_dtype, preprocess_image=preprocess_image)
|
| 538 |
+
return control
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
def load_controlnet_hunyuandit(controlnet_data, model_options={}):
|
| 543 |
+
model_config, operations, load_device, unet_dtype, manual_cast_dtype, offload_device = controlnet_config(controlnet_data, model_options=model_options)
|
| 544 |
+
|
| 545 |
+
control_model = comfy.ldm.hydit.controlnet.HunYuanControlNet(operations=operations, device=offload_device, dtype=unet_dtype)
|
| 546 |
+
control_model = controlnet_load_state_dict(control_model, controlnet_data)
|
| 547 |
+
|
| 548 |
+
latent_format = comfy.latent_formats.SDXL()
|
| 549 |
+
extra_conds = ['text_embedding_mask', 'encoder_hidden_states_t5', 'text_embedding_mask_t5', 'image_meta_size', 'style', 'cos_cis_img', 'sin_cis_img']
|
| 550 |
+
control = ControlNet(control_model, compression_ratio=1, latent_format=latent_format, load_device=load_device, manual_cast_dtype=manual_cast_dtype, extra_conds=extra_conds, strength_type=StrengthType.CONSTANT)
|
| 551 |
+
return control
|
| 552 |
+
|
| 553 |
+
def load_controlnet_flux_xlabs_mistoline(sd, mistoline=False, model_options={}):
|
| 554 |
+
model_config, operations, load_device, unet_dtype, manual_cast_dtype, offload_device = controlnet_config(sd, model_options=model_options)
|
| 555 |
+
control_model = comfy.ldm.flux.controlnet.ControlNetFlux(mistoline=mistoline, operations=operations, device=offload_device, dtype=unet_dtype, **model_config.unet_config)
|
| 556 |
+
control_model = controlnet_load_state_dict(control_model, sd)
|
| 557 |
+
extra_conds = ['y', 'guidance']
|
| 558 |
+
control = ControlNet(control_model, load_device=load_device, manual_cast_dtype=manual_cast_dtype, extra_conds=extra_conds)
|
| 559 |
+
return control
|
| 560 |
+
|
| 561 |
+
def load_controlnet_flux_instantx(sd, model_options={}):
|
| 562 |
+
new_sd = comfy.model_detection.convert_diffusers_mmdit(sd, "")
|
| 563 |
+
model_config, operations, load_device, unet_dtype, manual_cast_dtype, offload_device = controlnet_config(new_sd, model_options=model_options)
|
| 564 |
+
for k in sd:
|
| 565 |
+
new_sd[k] = sd[k]
|
| 566 |
+
|
| 567 |
+
num_union_modes = 0
|
| 568 |
+
union_cnet = "controlnet_mode_embedder.weight"
|
| 569 |
+
if union_cnet in new_sd:
|
| 570 |
+
num_union_modes = new_sd[union_cnet].shape[0]
|
| 571 |
+
|
| 572 |
+
control_latent_channels = new_sd.get("pos_embed_input.weight").shape[1] // 4
|
| 573 |
+
concat_mask = False
|
| 574 |
+
if control_latent_channels == 17:
|
| 575 |
+
concat_mask = True
|
| 576 |
+
|
| 577 |
+
control_model = comfy.ldm.flux.controlnet.ControlNetFlux(latent_input=True, num_union_modes=num_union_modes, control_latent_channels=control_latent_channels, operations=operations, device=offload_device, dtype=unet_dtype, **model_config.unet_config)
|
| 578 |
+
control_model = controlnet_load_state_dict(control_model, new_sd)
|
| 579 |
+
|
| 580 |
+
latent_format = comfy.latent_formats.Flux()
|
| 581 |
+
extra_conds = ['y', 'guidance']
|
| 582 |
+
control = ControlNet(control_model, compression_ratio=1, latent_format=latent_format, concat_mask=concat_mask, load_device=load_device, manual_cast_dtype=manual_cast_dtype, extra_conds=extra_conds)
|
| 583 |
+
return control
|
| 584 |
+
|
| 585 |
+
def convert_mistoline(sd):
|
| 586 |
+
return comfy.utils.state_dict_prefix_replace(sd, {"single_controlnet_blocks.": "controlnet_single_blocks."})
|
| 587 |
+
|
| 588 |
+
|
| 589 |
+
def load_controlnet_state_dict(state_dict, model=None, model_options={}):
|
| 590 |
+
controlnet_data = state_dict
|
| 591 |
+
if 'after_proj_list.18.bias' in controlnet_data.keys(): #Hunyuan DiT
|
| 592 |
+
return load_controlnet_hunyuandit(controlnet_data, model_options=model_options)
|
| 593 |
+
|
| 594 |
+
if "lora_controlnet" in controlnet_data:
|
| 595 |
+
return ControlLora(controlnet_data, model_options=model_options)
|
| 596 |
+
|
| 597 |
+
controlnet_config = None
|
| 598 |
+
supported_inference_dtypes = None
|
| 599 |
+
|
| 600 |
+
if "controlnet_cond_embedding.conv_in.weight" in controlnet_data: #diffusers format
|
| 601 |
+
controlnet_config = comfy.model_detection.unet_config_from_diffusers_unet(controlnet_data)
|
| 602 |
+
diffusers_keys = comfy.utils.unet_to_diffusers(controlnet_config)
|
| 603 |
+
diffusers_keys["controlnet_mid_block.weight"] = "middle_block_out.0.weight"
|
| 604 |
+
diffusers_keys["controlnet_mid_block.bias"] = "middle_block_out.0.bias"
|
| 605 |
+
|
| 606 |
+
count = 0
|
| 607 |
+
loop = True
|
| 608 |
+
while loop:
|
| 609 |
+
suffix = [".weight", ".bias"]
|
| 610 |
+
for s in suffix:
|
| 611 |
+
k_in = "controlnet_down_blocks.{}{}".format(count, s)
|
| 612 |
+
k_out = "zero_convs.{}.0{}".format(count, s)
|
| 613 |
+
if k_in not in controlnet_data:
|
| 614 |
+
loop = False
|
| 615 |
+
break
|
| 616 |
+
diffusers_keys[k_in] = k_out
|
| 617 |
+
count += 1
|
| 618 |
+
|
| 619 |
+
count = 0
|
| 620 |
+
loop = True
|
| 621 |
+
while loop:
|
| 622 |
+
suffix = [".weight", ".bias"]
|
| 623 |
+
for s in suffix:
|
| 624 |
+
if count == 0:
|
| 625 |
+
k_in = "controlnet_cond_embedding.conv_in{}".format(s)
|
| 626 |
+
else:
|
| 627 |
+
k_in = "controlnet_cond_embedding.blocks.{}{}".format(count - 1, s)
|
| 628 |
+
k_out = "input_hint_block.{}{}".format(count * 2, s)
|
| 629 |
+
if k_in not in controlnet_data:
|
| 630 |
+
k_in = "controlnet_cond_embedding.conv_out{}".format(s)
|
| 631 |
+
loop = False
|
| 632 |
+
diffusers_keys[k_in] = k_out
|
| 633 |
+
count += 1
|
| 634 |
+
|
| 635 |
+
new_sd = {}
|
| 636 |
+
for k in diffusers_keys:
|
| 637 |
+
if k in controlnet_data:
|
| 638 |
+
new_sd[diffusers_keys[k]] = controlnet_data.pop(k)
|
| 639 |
+
|
| 640 |
+
if "control_add_embedding.linear_1.bias" in controlnet_data: #Union Controlnet
|
| 641 |
+
controlnet_config["union_controlnet_num_control_type"] = controlnet_data["task_embedding"].shape[0]
|
| 642 |
+
for k in list(controlnet_data.keys()):
|
| 643 |
+
new_k = k.replace('.attn.in_proj_', '.attn.in_proj.')
|
| 644 |
+
new_sd[new_k] = controlnet_data.pop(k)
|
| 645 |
+
|
| 646 |
+
leftover_keys = controlnet_data.keys()
|
| 647 |
+
if len(leftover_keys) > 0:
|
| 648 |
+
logging.warning("leftover keys: {}".format(leftover_keys))
|
| 649 |
+
controlnet_data = new_sd
|
| 650 |
+
elif "controlnet_blocks.0.weight" in controlnet_data:
|
| 651 |
+
if "double_blocks.0.img_attn.norm.key_norm.scale" in controlnet_data:
|
| 652 |
+
return load_controlnet_flux_xlabs_mistoline(controlnet_data, model_options=model_options)
|
| 653 |
+
elif "pos_embed_input.proj.weight" in controlnet_data:
|
| 654 |
+
if "transformer_blocks.0.adaLN_modulation.1.bias" in controlnet_data:
|
| 655 |
+
return load_controlnet_sd35(controlnet_data, model_options=model_options) #Stability sd3.5 format
|
| 656 |
+
else:
|
| 657 |
+
return load_controlnet_mmdit(controlnet_data, model_options=model_options) #SD3 diffusers controlnet
|
| 658 |
+
elif "controlnet_x_embedder.weight" in controlnet_data:
|
| 659 |
+
return load_controlnet_flux_instantx(controlnet_data, model_options=model_options)
|
| 660 |
+
elif "controlnet_blocks.0.linear.weight" in controlnet_data: #mistoline flux
|
| 661 |
+
return load_controlnet_flux_xlabs_mistoline(convert_mistoline(controlnet_data), mistoline=True, model_options=model_options)
|
| 662 |
+
|
| 663 |
+
pth_key = 'control_model.zero_convs.0.0.weight'
|
| 664 |
+
pth = False
|
| 665 |
+
key = 'zero_convs.0.0.weight'
|
| 666 |
+
if pth_key in controlnet_data:
|
| 667 |
+
pth = True
|
| 668 |
+
key = pth_key
|
| 669 |
+
prefix = "control_model."
|
| 670 |
+
elif key in controlnet_data:
|
| 671 |
+
prefix = ""
|
| 672 |
+
else:
|
| 673 |
+
net = load_t2i_adapter(controlnet_data, model_options=model_options)
|
| 674 |
+
if net is None:
|
| 675 |
+
logging.error("error could not detect control model type.")
|
| 676 |
+
return net
|
| 677 |
+
|
| 678 |
+
if controlnet_config is None:
|
| 679 |
+
model_config = comfy.model_detection.model_config_from_unet(controlnet_data, prefix, True)
|
| 680 |
+
supported_inference_dtypes = list(model_config.supported_inference_dtypes)
|
| 681 |
+
controlnet_config = model_config.unet_config
|
| 682 |
+
|
| 683 |
+
unet_dtype = model_options.get("dtype", None)
|
| 684 |
+
if unet_dtype is None:
|
| 685 |
+
weight_dtype = comfy.utils.weight_dtype(controlnet_data)
|
| 686 |
+
|
| 687 |
+
if supported_inference_dtypes is None:
|
| 688 |
+
supported_inference_dtypes = [comfy.model_management.unet_dtype()]
|
| 689 |
+
|
| 690 |
+
unet_dtype = comfy.model_management.unet_dtype(model_params=-1, supported_dtypes=supported_inference_dtypes, weight_dtype=weight_dtype)
|
| 691 |
+
|
| 692 |
+
load_device = comfy.model_management.get_torch_device()
|
| 693 |
+
|
| 694 |
+
manual_cast_dtype = comfy.model_management.unet_manual_cast(unet_dtype, load_device)
|
| 695 |
+
operations = model_options.get("custom_operations", None)
|
| 696 |
+
if operations is None:
|
| 697 |
+
operations = comfy.ops.pick_operations(unet_dtype, manual_cast_dtype)
|
| 698 |
+
|
| 699 |
+
controlnet_config["operations"] = operations
|
| 700 |
+
controlnet_config["dtype"] = unet_dtype
|
| 701 |
+
controlnet_config["device"] = comfy.model_management.unet_offload_device()
|
| 702 |
+
controlnet_config.pop("out_channels")
|
| 703 |
+
controlnet_config["hint_channels"] = controlnet_data["{}input_hint_block.0.weight".format(prefix)].shape[1]
|
| 704 |
+
control_model = comfy.cldm.cldm.ControlNet(**controlnet_config)
|
| 705 |
+
|
| 706 |
+
if pth:
|
| 707 |
+
if 'difference' in controlnet_data:
|
| 708 |
+
if model is not None:
|
| 709 |
+
comfy.model_management.load_models_gpu([model])
|
| 710 |
+
model_sd = model.model_state_dict()
|
| 711 |
+
for x in controlnet_data:
|
| 712 |
+
c_m = "control_model."
|
| 713 |
+
if x.startswith(c_m):
|
| 714 |
+
sd_key = "diffusion_model.{}".format(x[len(c_m):])
|
| 715 |
+
if sd_key in model_sd:
|
| 716 |
+
cd = controlnet_data[x]
|
| 717 |
+
cd += model_sd[sd_key].type(cd.dtype).to(cd.device)
|
| 718 |
+
else:
|
| 719 |
+
logging.warning("WARNING: Loaded a diff controlnet without a model. It will very likely not work.")
|
| 720 |
+
|
| 721 |
+
class WeightsLoader(torch.nn.Module):
|
| 722 |
+
pass
|
| 723 |
+
w = WeightsLoader()
|
| 724 |
+
w.control_model = control_model
|
| 725 |
+
missing, unexpected = w.load_state_dict(controlnet_data, strict=False)
|
| 726 |
+
else:
|
| 727 |
+
missing, unexpected = control_model.load_state_dict(controlnet_data, strict=False)
|
| 728 |
+
|
| 729 |
+
if len(missing) > 0:
|
| 730 |
+
logging.warning("missing controlnet keys: {}".format(missing))
|
| 731 |
+
|
| 732 |
+
if len(unexpected) > 0:
|
| 733 |
+
logging.debug("unexpected controlnet keys: {}".format(unexpected))
|
| 734 |
+
|
| 735 |
+
global_average_pooling = model_options.get("global_average_pooling", False)
|
| 736 |
+
control = ControlNet(control_model, global_average_pooling=global_average_pooling, load_device=load_device, manual_cast_dtype=manual_cast_dtype)
|
| 737 |
+
return control
|
| 738 |
+
|
| 739 |
+
def load_controlnet(ckpt_path, model=None, model_options={}):
|
| 740 |
+
model_options = model_options.copy()
|
| 741 |
+
if "global_average_pooling" not in model_options:
|
| 742 |
+
filename = os.path.splitext(ckpt_path)[0]
|
| 743 |
+
if filename.endswith("_shuffle") or filename.endswith("_shuffle_fp16"): #TODO: smarter way of enabling global_average_pooling
|
| 744 |
+
model_options["global_average_pooling"] = True
|
| 745 |
+
|
| 746 |
+
cnet = load_controlnet_state_dict(comfy.utils.load_torch_file(ckpt_path, safe_load=True), model=model, model_options=model_options)
|
| 747 |
+
if cnet is None:
|
| 748 |
+
logging.error("error checkpoint does not contain controlnet or t2i adapter data {}".format(ckpt_path))
|
| 749 |
+
return cnet
|
| 750 |
+
|
| 751 |
+
class T2IAdapter(ControlBase):
|
| 752 |
+
def __init__(self, t2i_model, channels_in, compression_ratio, upscale_algorithm, device=None):
|
| 753 |
+
super().__init__()
|
| 754 |
+
self.t2i_model = t2i_model
|
| 755 |
+
self.channels_in = channels_in
|
| 756 |
+
self.control_input = None
|
| 757 |
+
self.compression_ratio = compression_ratio
|
| 758 |
+
self.upscale_algorithm = upscale_algorithm
|
| 759 |
+
if device is None:
|
| 760 |
+
device = comfy.model_management.get_torch_device()
|
| 761 |
+
self.device = device
|
| 762 |
+
|
| 763 |
+
def scale_image_to(self, width, height):
|
| 764 |
+
unshuffle_amount = self.t2i_model.unshuffle_amount
|
| 765 |
+
width = math.ceil(width / unshuffle_amount) * unshuffle_amount
|
| 766 |
+
height = math.ceil(height / unshuffle_amount) * unshuffle_amount
|
| 767 |
+
return width, height
|
| 768 |
+
|
| 769 |
+
def get_control(self, x_noisy, t, cond, batched_number, transformer_options):
|
| 770 |
+
control_prev = None
|
| 771 |
+
if self.previous_controlnet is not None:
|
| 772 |
+
control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number, transformer_options)
|
| 773 |
+
|
| 774 |
+
if self.timestep_range is not None:
|
| 775 |
+
if t[0] > self.timestep_range[0] or t[0] < self.timestep_range[1]:
|
| 776 |
+
if control_prev is not None:
|
| 777 |
+
return control_prev
|
| 778 |
+
else:
|
| 779 |
+
return None
|
| 780 |
+
|
| 781 |
+
if self.cond_hint is None or x_noisy.shape[2] * self.compression_ratio != self.cond_hint.shape[2] or x_noisy.shape[3] * self.compression_ratio != self.cond_hint.shape[3]:
|
| 782 |
+
if self.cond_hint is not None:
|
| 783 |
+
del self.cond_hint
|
| 784 |
+
self.control_input = None
|
| 785 |
+
self.cond_hint = None
|
| 786 |
+
width, height = self.scale_image_to(x_noisy.shape[3] * self.compression_ratio, x_noisy.shape[2] * self.compression_ratio)
|
| 787 |
+
self.cond_hint = comfy.utils.common_upscale(self.cond_hint_original, width, height, self.upscale_algorithm, "center").float().to(self.device)
|
| 788 |
+
if self.channels_in == 1 and self.cond_hint.shape[1] > 1:
|
| 789 |
+
self.cond_hint = torch.mean(self.cond_hint, 1, keepdim=True)
|
| 790 |
+
if x_noisy.shape[0] != self.cond_hint.shape[0]:
|
| 791 |
+
self.cond_hint = broadcast_image_to(self.cond_hint, x_noisy.shape[0], batched_number)
|
| 792 |
+
if self.control_input is None:
|
| 793 |
+
self.t2i_model.to(x_noisy.dtype)
|
| 794 |
+
self.t2i_model.to(self.device)
|
| 795 |
+
self.control_input = self.t2i_model(self.cond_hint.to(x_noisy.dtype))
|
| 796 |
+
self.t2i_model.cpu()
|
| 797 |
+
|
| 798 |
+
control_input = {}
|
| 799 |
+
for k in self.control_input:
|
| 800 |
+
control_input[k] = list(map(lambda a: None if a is None else a.clone(), self.control_input[k]))
|
| 801 |
+
|
| 802 |
+
return self.control_merge(control_input, control_prev, x_noisy.dtype)
|
| 803 |
+
|
| 804 |
+
def copy(self):
|
| 805 |
+
c = T2IAdapter(self.t2i_model, self.channels_in, self.compression_ratio, self.upscale_algorithm)
|
| 806 |
+
self.copy_to(c)
|
| 807 |
+
return c
|
| 808 |
+
|
| 809 |
+
def load_t2i_adapter(t2i_data, model_options={}): #TODO: model_options
|
| 810 |
+
compression_ratio = 8
|
| 811 |
+
upscale_algorithm = 'nearest-exact'
|
| 812 |
+
|
| 813 |
+
if 'adapter' in t2i_data:
|
| 814 |
+
t2i_data = t2i_data['adapter']
|
| 815 |
+
if 'adapter.body.0.resnets.0.block1.weight' in t2i_data: #diffusers format
|
| 816 |
+
prefix_replace = {}
|
| 817 |
+
for i in range(4):
|
| 818 |
+
for j in range(2):
|
| 819 |
+
prefix_replace["adapter.body.{}.resnets.{}.".format(i, j)] = "body.{}.".format(i * 2 + j)
|
| 820 |
+
prefix_replace["adapter.body.{}.".format(i, )] = "body.{}.".format(i * 2)
|
| 821 |
+
prefix_replace["adapter."] = ""
|
| 822 |
+
t2i_data = comfy.utils.state_dict_prefix_replace(t2i_data, prefix_replace)
|
| 823 |
+
keys = t2i_data.keys()
|
| 824 |
+
|
| 825 |
+
if "body.0.in_conv.weight" in keys:
|
| 826 |
+
cin = t2i_data['body.0.in_conv.weight'].shape[1]
|
| 827 |
+
model_ad = comfy.t2i_adapter.adapter.Adapter_light(cin=cin, channels=[320, 640, 1280, 1280], nums_rb=4)
|
| 828 |
+
elif 'conv_in.weight' in keys:
|
| 829 |
+
cin = t2i_data['conv_in.weight'].shape[1]
|
| 830 |
+
channel = t2i_data['conv_in.weight'].shape[0]
|
| 831 |
+
ksize = t2i_data['body.0.block2.weight'].shape[2]
|
| 832 |
+
use_conv = False
|
| 833 |
+
down_opts = list(filter(lambda a: a.endswith("down_opt.op.weight"), keys))
|
| 834 |
+
if len(down_opts) > 0:
|
| 835 |
+
use_conv = True
|
| 836 |
+
xl = False
|
| 837 |
+
if cin == 256 or cin == 768:
|
| 838 |
+
xl = True
|
| 839 |
+
model_ad = comfy.t2i_adapter.adapter.Adapter(cin=cin, channels=[channel, channel*2, channel*4, channel*4][:4], nums_rb=2, ksize=ksize, sk=True, use_conv=use_conv, xl=xl)
|
| 840 |
+
elif "backbone.0.0.weight" in keys:
|
| 841 |
+
model_ad = comfy.ldm.cascade.controlnet.ControlNet(c_in=t2i_data['backbone.0.0.weight'].shape[1], proj_blocks=[0, 4, 8, 12, 51, 55, 59, 63])
|
| 842 |
+
compression_ratio = 32
|
| 843 |
+
upscale_algorithm = 'bilinear'
|
| 844 |
+
elif "backbone.10.blocks.0.weight" in keys:
|
| 845 |
+
model_ad = comfy.ldm.cascade.controlnet.ControlNet(c_in=t2i_data['backbone.0.weight'].shape[1], bottleneck_mode="large", proj_blocks=[0, 4, 8, 12, 51, 55, 59, 63])
|
| 846 |
+
compression_ratio = 1
|
| 847 |
+
upscale_algorithm = 'nearest-exact'
|
| 848 |
+
else:
|
| 849 |
+
return None
|
| 850 |
+
|
| 851 |
+
missing, unexpected = model_ad.load_state_dict(t2i_data)
|
| 852 |
+
if len(missing) > 0:
|
| 853 |
+
logging.warning("t2i missing {}".format(missing))
|
| 854 |
+
|
| 855 |
+
if len(unexpected) > 0:
|
| 856 |
+
logging.debug("t2i unexpected {}".format(unexpected))
|
| 857 |
+
|
| 858 |
+
return T2IAdapter(model_ad, model_ad.input_channels, compression_ratio, upscale_algorithm)
|
comfy/diffusers_convert.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import torch
|
| 3 |
+
import logging
|
| 4 |
+
|
| 5 |
+
# conversion code from https://github.com/huggingface/diffusers/blob/main/scripts/convert_diffusers_to_original_stable_diffusion.py
|
| 6 |
+
|
| 7 |
+
# ================#
|
| 8 |
+
# VAE Conversion #
|
| 9 |
+
# ================#
|
| 10 |
+
|
| 11 |
+
vae_conversion_map = [
|
| 12 |
+
# (stable-diffusion, HF Diffusers)
|
| 13 |
+
("nin_shortcut", "conv_shortcut"),
|
| 14 |
+
("norm_out", "conv_norm_out"),
|
| 15 |
+
("mid.attn_1.", "mid_block.attentions.0."),
|
| 16 |
+
]
|
| 17 |
+
|
| 18 |
+
for i in range(4):
|
| 19 |
+
# down_blocks have two resnets
|
| 20 |
+
for j in range(2):
|
| 21 |
+
hf_down_prefix = f"encoder.down_blocks.{i}.resnets.{j}."
|
| 22 |
+
sd_down_prefix = f"encoder.down.{i}.block.{j}."
|
| 23 |
+
vae_conversion_map.append((sd_down_prefix, hf_down_prefix))
|
| 24 |
+
|
| 25 |
+
if i < 3:
|
| 26 |
+
hf_downsample_prefix = f"down_blocks.{i}.downsamplers.0."
|
| 27 |
+
sd_downsample_prefix = f"down.{i}.downsample."
|
| 28 |
+
vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix))
|
| 29 |
+
|
| 30 |
+
hf_upsample_prefix = f"up_blocks.{i}.upsamplers.0."
|
| 31 |
+
sd_upsample_prefix = f"up.{3 - i}.upsample."
|
| 32 |
+
vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix))
|
| 33 |
+
|
| 34 |
+
# up_blocks have three resnets
|
| 35 |
+
# also, up blocks in hf are numbered in reverse from sd
|
| 36 |
+
for j in range(3):
|
| 37 |
+
hf_up_prefix = f"decoder.up_blocks.{i}.resnets.{j}."
|
| 38 |
+
sd_up_prefix = f"decoder.up.{3 - i}.block.{j}."
|
| 39 |
+
vae_conversion_map.append((sd_up_prefix, hf_up_prefix))
|
| 40 |
+
|
| 41 |
+
# this part accounts for mid blocks in both the encoder and the decoder
|
| 42 |
+
for i in range(2):
|
| 43 |
+
hf_mid_res_prefix = f"mid_block.resnets.{i}."
|
| 44 |
+
sd_mid_res_prefix = f"mid.block_{i + 1}."
|
| 45 |
+
vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix))
|
| 46 |
+
|
| 47 |
+
vae_conversion_map_attn = [
|
| 48 |
+
# (stable-diffusion, HF Diffusers)
|
| 49 |
+
("norm.", "group_norm."),
|
| 50 |
+
("q.", "query."),
|
| 51 |
+
("k.", "key."),
|
| 52 |
+
("v.", "value."),
|
| 53 |
+
("q.", "to_q."),
|
| 54 |
+
("k.", "to_k."),
|
| 55 |
+
("v.", "to_v."),
|
| 56 |
+
("proj_out.", "to_out.0."),
|
| 57 |
+
("proj_out.", "proj_attn."),
|
| 58 |
+
]
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def reshape_weight_for_sd(w, conv3d=False):
|
| 62 |
+
# convert HF linear weights to SD conv2d weights
|
| 63 |
+
if conv3d:
|
| 64 |
+
return w.reshape(*w.shape, 1, 1, 1)
|
| 65 |
+
else:
|
| 66 |
+
return w.reshape(*w.shape, 1, 1)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def convert_vae_state_dict(vae_state_dict):
|
| 70 |
+
mapping = {k: k for k in vae_state_dict.keys()}
|
| 71 |
+
conv3d = False
|
| 72 |
+
for k, v in mapping.items():
|
| 73 |
+
for sd_part, hf_part in vae_conversion_map:
|
| 74 |
+
v = v.replace(hf_part, sd_part)
|
| 75 |
+
if v.endswith(".conv.weight"):
|
| 76 |
+
if not conv3d and vae_state_dict[k].ndim == 5:
|
| 77 |
+
conv3d = True
|
| 78 |
+
mapping[k] = v
|
| 79 |
+
for k, v in mapping.items():
|
| 80 |
+
if "attentions" in k:
|
| 81 |
+
for sd_part, hf_part in vae_conversion_map_attn:
|
| 82 |
+
v = v.replace(hf_part, sd_part)
|
| 83 |
+
mapping[k] = v
|
| 84 |
+
new_state_dict = {v: vae_state_dict[k] for k, v in mapping.items()}
|
| 85 |
+
weights_to_convert = ["q", "k", "v", "proj_out"]
|
| 86 |
+
for k, v in new_state_dict.items():
|
| 87 |
+
for weight_name in weights_to_convert:
|
| 88 |
+
if f"mid.attn_1.{weight_name}.weight" in k:
|
| 89 |
+
logging.debug(f"Reshaping {k} for SD format")
|
| 90 |
+
new_state_dict[k] = reshape_weight_for_sd(v, conv3d=conv3d)
|
| 91 |
+
return new_state_dict
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
# =========================#
|
| 95 |
+
# Text Encoder Conversion #
|
| 96 |
+
# =========================#
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
textenc_conversion_lst = [
|
| 100 |
+
# (stable-diffusion, HF Diffusers)
|
| 101 |
+
("resblocks.", "text_model.encoder.layers."),
|
| 102 |
+
("ln_1", "layer_norm1"),
|
| 103 |
+
("ln_2", "layer_norm2"),
|
| 104 |
+
(".c_fc.", ".fc1."),
|
| 105 |
+
(".c_proj.", ".fc2."),
|
| 106 |
+
(".attn", ".self_attn"),
|
| 107 |
+
("ln_final.", "transformer.text_model.final_layer_norm."),
|
| 108 |
+
("token_embedding.weight", "transformer.text_model.embeddings.token_embedding.weight"),
|
| 109 |
+
("positional_embedding", "transformer.text_model.embeddings.position_embedding.weight"),
|
| 110 |
+
]
|
| 111 |
+
protected = {re.escape(x[1]): x[0] for x in textenc_conversion_lst}
|
| 112 |
+
textenc_pattern = re.compile("|".join(protected.keys()))
|
| 113 |
+
|
| 114 |
+
# Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp
|
| 115 |
+
code2idx = {"q": 0, "k": 1, "v": 2}
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
# This function exists because at the time of writing torch.cat can't do fp8 with cuda
|
| 119 |
+
def cat_tensors(tensors):
|
| 120 |
+
x = 0
|
| 121 |
+
for t in tensors:
|
| 122 |
+
x += t.shape[0]
|
| 123 |
+
|
| 124 |
+
shape = [x] + list(tensors[0].shape)[1:]
|
| 125 |
+
out = torch.empty(shape, device=tensors[0].device, dtype=tensors[0].dtype)
|
| 126 |
+
|
| 127 |
+
x = 0
|
| 128 |
+
for t in tensors:
|
| 129 |
+
out[x:x + t.shape[0]] = t
|
| 130 |
+
x += t.shape[0]
|
| 131 |
+
|
| 132 |
+
return out
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def convert_text_enc_state_dict_v20(text_enc_dict, prefix=""):
|
| 136 |
+
new_state_dict = {}
|
| 137 |
+
capture_qkv_weight = {}
|
| 138 |
+
capture_qkv_bias = {}
|
| 139 |
+
for k, v in text_enc_dict.items():
|
| 140 |
+
if not k.startswith(prefix):
|
| 141 |
+
continue
|
| 142 |
+
if (
|
| 143 |
+
k.endswith(".self_attn.q_proj.weight")
|
| 144 |
+
or k.endswith(".self_attn.k_proj.weight")
|
| 145 |
+
or k.endswith(".self_attn.v_proj.weight")
|
| 146 |
+
):
|
| 147 |
+
k_pre = k[: -len(".q_proj.weight")]
|
| 148 |
+
k_code = k[-len("q_proj.weight")]
|
| 149 |
+
if k_pre not in capture_qkv_weight:
|
| 150 |
+
capture_qkv_weight[k_pre] = [None, None, None]
|
| 151 |
+
capture_qkv_weight[k_pre][code2idx[k_code]] = v
|
| 152 |
+
continue
|
| 153 |
+
|
| 154 |
+
if (
|
| 155 |
+
k.endswith(".self_attn.q_proj.bias")
|
| 156 |
+
or k.endswith(".self_attn.k_proj.bias")
|
| 157 |
+
or k.endswith(".self_attn.v_proj.bias")
|
| 158 |
+
):
|
| 159 |
+
k_pre = k[: -len(".q_proj.bias")]
|
| 160 |
+
k_code = k[-len("q_proj.bias")]
|
| 161 |
+
if k_pre not in capture_qkv_bias:
|
| 162 |
+
capture_qkv_bias[k_pre] = [None, None, None]
|
| 163 |
+
capture_qkv_bias[k_pre][code2idx[k_code]] = v
|
| 164 |
+
continue
|
| 165 |
+
|
| 166 |
+
text_proj = "transformer.text_projection.weight"
|
| 167 |
+
if k.endswith(text_proj):
|
| 168 |
+
new_state_dict[k.replace(text_proj, "text_projection")] = v.transpose(0, 1).contiguous()
|
| 169 |
+
else:
|
| 170 |
+
relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k)
|
| 171 |
+
new_state_dict[relabelled_key] = v
|
| 172 |
+
|
| 173 |
+
for k_pre, tensors in capture_qkv_weight.items():
|
| 174 |
+
if None in tensors:
|
| 175 |
+
raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing")
|
| 176 |
+
relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k_pre)
|
| 177 |
+
new_state_dict[relabelled_key + ".in_proj_weight"] = cat_tensors(tensors)
|
| 178 |
+
|
| 179 |
+
for k_pre, tensors in capture_qkv_bias.items():
|
| 180 |
+
if None in tensors:
|
| 181 |
+
raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing")
|
| 182 |
+
relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k_pre)
|
| 183 |
+
new_state_dict[relabelled_key + ".in_proj_bias"] = cat_tensors(tensors)
|
| 184 |
+
|
| 185 |
+
return new_state_dict
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def convert_text_enc_state_dict(text_enc_dict):
|
| 189 |
+
return text_enc_dict
|