Spaces:
No application file
No application file
Commit
·
2d2569d
0
Parent(s):
Initial clean push for Hugging Face Space
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .ci/a +0 -0
- .ci/update_windows/update.py +117 -0
- .ci/update_windows/update_comfyui.bat +8 -0
- .ci/windows_base_files/README_VERY_IMPORTANT.txt +31 -0
- .ci/windows_base_files/run_cpu.bat +2 -0
- .ci/windows_base_files/run_nvidia_gpu.bat +2 -0
- .github/ISSUE_TEMPLATE/bug-report.yml +48 -0
- .github/ISSUE_TEMPLATE/config.yml +8 -0
- .github/ISSUE_TEMPLATE/feature-request.yml +32 -0
- .github/ISSUE_TEMPLATE/user-support.yml +32 -0
- .github/workflows/pylint.yml +23 -0
- .github/workflows/stable-release.yml +110 -0
- .github/workflows/test-browser.yml +76 -0
- .github/workflows/test-build.yml +31 -0
- .github/workflows/test-ui.yaml +30 -0
- .github/workflows/windows_release_dependencies.yml +71 -0
- .github/workflows/windows_release_nightly_pytorch.yml +90 -0
- .github/workflows/windows_release_package.yml +100 -0
- .gitignore +44 -0
- .gradio/certificate.pem +31 -0
- .pylintrc +3 -0
- CODEOWNERS +1 -0
- CONTRIBUTING.md +41 -0
- LICENSE +674 -0
- README.md +238 -0
- app.py +420 -0
- app/__init__.py +0 -0
- app/app_settings.py +54 -0
- app/frontend_management.py +188 -0
- app/user_manager.py +205 -0
- comfy/checkpoint_pickle.py +13 -0
- comfy/cldm/cldm.py +437 -0
- comfy/cldm/control_types.py +10 -0
- comfy/cldm/mmdit.py +77 -0
- comfy/cli_args.py +180 -0
- comfy/clip_config_bigg.json +23 -0
- comfy/clip_model.py +196 -0
- comfy/clip_vision.py +121 -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/conds.py +83 -0
- comfy/controlnet.py +610 -0
- comfy/diffusers_convert.py +281 -0
- comfy/diffusers_load.py +36 -0
- comfy/extra_samplers/uni_pc.py +875 -0
- comfy/gligen.py +343 -0
- comfy/k_diffusion/deis.py +121 -0
- comfy/k_diffusion/sampling.py +1050 -0
.ci/a
ADDED
File without changes
|
.ci/update_windows/update.py
ADDED
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pygit2
|
2 |
+
from datetime import datetime
|
3 |
+
import sys
|
4 |
+
import os
|
5 |
+
import shutil
|
6 |
+
import filecmp
|
7 |
+
|
8 |
+
def pull(repo, remote_name='origin', branch='master'):
|
9 |
+
for remote in repo.remotes:
|
10 |
+
if remote.name == remote_name:
|
11 |
+
remote.fetch()
|
12 |
+
remote_master_id = repo.lookup_reference('refs/remotes/origin/%s' % (branch)).target
|
13 |
+
merge_result, _ = repo.merge_analysis(remote_master_id)
|
14 |
+
# Up to date, do nothing
|
15 |
+
if merge_result & pygit2.GIT_MERGE_ANALYSIS_UP_TO_DATE:
|
16 |
+
return
|
17 |
+
# We can just fastforward
|
18 |
+
elif merge_result & pygit2.GIT_MERGE_ANALYSIS_FASTFORWARD:
|
19 |
+
repo.checkout_tree(repo.get(remote_master_id))
|
20 |
+
try:
|
21 |
+
master_ref = repo.lookup_reference('refs/heads/%s' % (branch))
|
22 |
+
master_ref.set_target(remote_master_id)
|
23 |
+
except KeyError:
|
24 |
+
repo.create_branch(branch, repo.get(remote_master_id))
|
25 |
+
repo.head.set_target(remote_master_id)
|
26 |
+
elif merge_result & pygit2.GIT_MERGE_ANALYSIS_NORMAL:
|
27 |
+
repo.merge(remote_master_id)
|
28 |
+
|
29 |
+
if repo.index.conflicts is not None:
|
30 |
+
for conflict in repo.index.conflicts:
|
31 |
+
print('Conflicts found in:', conflict[0].path)
|
32 |
+
raise AssertionError('Conflicts, ahhhhh!!')
|
33 |
+
|
34 |
+
user = repo.default_signature
|
35 |
+
tree = repo.index.write_tree()
|
36 |
+
commit = repo.create_commit('HEAD',
|
37 |
+
user,
|
38 |
+
user,
|
39 |
+
'Merge!',
|
40 |
+
tree,
|
41 |
+
[repo.head.target, remote_master_id])
|
42 |
+
# We need to do this or git CLI will think we are still merging.
|
43 |
+
repo.state_cleanup()
|
44 |
+
else:
|
45 |
+
raise AssertionError('Unknown merge analysis result')
|
46 |
+
|
47 |
+
pygit2.option(pygit2.GIT_OPT_SET_OWNER_VALIDATION, 0)
|
48 |
+
repo_path = str(sys.argv[1])
|
49 |
+
repo = pygit2.Repository(repo_path)
|
50 |
+
ident = pygit2.Signature('comfyui', 'comfy@ui')
|
51 |
+
try:
|
52 |
+
print("stashing current changes")
|
53 |
+
repo.stash(ident)
|
54 |
+
except KeyError:
|
55 |
+
print("nothing to stash")
|
56 |
+
backup_branch_name = 'backup_branch_{}'.format(datetime.today().strftime('%Y-%m-%d_%H_%M_%S'))
|
57 |
+
print("creating backup branch: {}".format(backup_branch_name))
|
58 |
+
try:
|
59 |
+
repo.branches.local.create(backup_branch_name, repo.head.peel())
|
60 |
+
except:
|
61 |
+
pass
|
62 |
+
|
63 |
+
print("checking out master branch")
|
64 |
+
branch = repo.lookup_branch('master')
|
65 |
+
if branch is None:
|
66 |
+
ref = repo.lookup_reference('refs/remotes/origin/master')
|
67 |
+
repo.checkout(ref)
|
68 |
+
branch = repo.lookup_branch('master')
|
69 |
+
if branch is None:
|
70 |
+
repo.create_branch('master', repo.get(ref.target))
|
71 |
+
else:
|
72 |
+
ref = repo.lookup_reference(branch.name)
|
73 |
+
repo.checkout(ref)
|
74 |
+
|
75 |
+
print("pulling latest changes")
|
76 |
+
pull(repo)
|
77 |
+
|
78 |
+
print("Done!")
|
79 |
+
|
80 |
+
self_update = True
|
81 |
+
if len(sys.argv) > 2:
|
82 |
+
self_update = '--skip_self_update' not in sys.argv
|
83 |
+
|
84 |
+
update_py_path = os.path.realpath(__file__)
|
85 |
+
repo_update_py_path = os.path.join(repo_path, ".ci/update_windows/update.py")
|
86 |
+
|
87 |
+
cur_path = os.path.dirname(update_py_path)
|
88 |
+
|
89 |
+
|
90 |
+
req_path = os.path.join(cur_path, "current_requirements.txt")
|
91 |
+
repo_req_path = os.path.join(repo_path, "requirements.txt")
|
92 |
+
|
93 |
+
|
94 |
+
def files_equal(file1, file2):
|
95 |
+
try:
|
96 |
+
return filecmp.cmp(file1, file2, shallow=False)
|
97 |
+
except:
|
98 |
+
return False
|
99 |
+
|
100 |
+
def file_size(f):
|
101 |
+
try:
|
102 |
+
return os.path.getsize(f)
|
103 |
+
except:
|
104 |
+
return 0
|
105 |
+
|
106 |
+
|
107 |
+
if self_update and not files_equal(update_py_path, repo_update_py_path) and file_size(repo_update_py_path) > 10:
|
108 |
+
shutil.copy(repo_update_py_path, os.path.join(cur_path, "update_new.py"))
|
109 |
+
exit()
|
110 |
+
|
111 |
+
if not os.path.exists(req_path) or not files_equal(repo_req_path, req_path):
|
112 |
+
import subprocess
|
113 |
+
try:
|
114 |
+
subprocess.check_call([sys.executable, '-s', '-m', 'pip', 'install', '-r', repo_req_path])
|
115 |
+
shutil.copy(repo_req_path, req_path)
|
116 |
+
except:
|
117 |
+
pass
|
.ci/update_windows/update_comfyui.bat
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
@echo off
|
2 |
+
..\python_embeded\python.exe .\update.py ..\ComfyUI\
|
3 |
+
if exist update_new.py (
|
4 |
+
move /y update_new.py update.py
|
5 |
+
echo Running updater again since it got updated.
|
6 |
+
..\python_embeded\python.exe .\update.py ..\ComfyUI\ --skip_self_update
|
7 |
+
)
|
8 |
+
if "%~1"=="" pause
|
.ci/windows_base_files/README_VERY_IMPORTANT.txt
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
HOW TO RUN:
|
2 |
+
|
3 |
+
if you have a NVIDIA gpu:
|
4 |
+
|
5 |
+
run_nvidia_gpu.bat
|
6 |
+
|
7 |
+
|
8 |
+
|
9 |
+
To run it in slow CPU mode:
|
10 |
+
|
11 |
+
run_cpu.bat
|
12 |
+
|
13 |
+
|
14 |
+
|
15 |
+
IF YOU GET A RED ERROR IN THE UI MAKE SURE YOU HAVE A MODEL/CHECKPOINT IN: ComfyUI\models\checkpoints
|
16 |
+
|
17 |
+
You can download the stable diffusion 1.5 one from: https://huggingface.co/runwayml/stable-diffusion-v1-5/blob/main/v1-5-pruned-emaonly.ckpt
|
18 |
+
|
19 |
+
|
20 |
+
RECOMMENDED WAY TO UPDATE:
|
21 |
+
To update the ComfyUI code: update\update_comfyui.bat
|
22 |
+
|
23 |
+
|
24 |
+
|
25 |
+
To update ComfyUI with the python dependencies, note that you should ONLY run this if you have issues with python dependencies.
|
26 |
+
update\update_comfyui_and_python_dependencies.bat
|
27 |
+
|
28 |
+
|
29 |
+
TO SHARE MODELS BETWEEN COMFYUI AND ANOTHER UI:
|
30 |
+
In the ComfyUI directory you will find a file: extra_model_paths.yaml.example
|
31 |
+
Rename this file to: extra_model_paths.yaml and edit it with your favorite text editor.
|
.ci/windows_base_files/run_cpu.bat
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
.\python_embeded\python.exe -s ComfyUI\main.py --cpu --windows-standalone-build
|
2 |
+
pause
|
.ci/windows_base_files/run_nvidia_gpu.bat
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
.\python_embeded\python.exe -s ComfyUI\main.py --windows-standalone-build
|
2 |
+
pause
|
.github/ISSUE_TEMPLATE/bug-report.yml
ADDED
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: Bug Report
|
2 |
+
description: "Something is broken inside of ComfyUI. (Do not use this if you're just having issues and need help, or if the issue relates to a custom node)"
|
3 |
+
labels: ["Potential Bug"]
|
4 |
+
body:
|
5 |
+
- type: markdown
|
6 |
+
attributes:
|
7 |
+
value: |
|
8 |
+
Before submitting a **Bug Report**, please ensure the following:
|
9 |
+
|
10 |
+
- **1:** You are running the latest version of ComfyUI.
|
11 |
+
- **2:** You have looked at the existing bug reports and made sure this isn't already reported.
|
12 |
+
- **3:** You confirmed that the bug is not caused by a custom node. You can disable all custom nodes by passing
|
13 |
+
`--disable-all-custom-nodes` command line argument.
|
14 |
+
- **4:** This is an actual bug in ComfyUI, not just a support question. A bug is when you can specify exact
|
15 |
+
steps to replicate what went wrong and others will be able to repeat your steps and see the same issue happen.
|
16 |
+
|
17 |
+
If unsure, ask on the [ComfyUI Matrix Space](https://app.element.io/#/room/%23comfyui_space%3Amatrix.org) or the [Comfy Org Discord](https://discord.gg/comfyorg) first.
|
18 |
+
- type: textarea
|
19 |
+
attributes:
|
20 |
+
label: Expected Behavior
|
21 |
+
description: "What you expected to happen."
|
22 |
+
validations:
|
23 |
+
required: true
|
24 |
+
- type: textarea
|
25 |
+
attributes:
|
26 |
+
label: Actual Behavior
|
27 |
+
description: "What actually happened. Please include a screenshot of the issue if possible."
|
28 |
+
validations:
|
29 |
+
required: true
|
30 |
+
- type: textarea
|
31 |
+
attributes:
|
32 |
+
label: Steps to Reproduce
|
33 |
+
description: "Describe how to reproduce the issue. Please be sure to attach a workflow JSON or PNG, ideally one that doesn't require custom nodes to test. If the bug open happens when certain custom nodes are used, most likely that custom node is what has the bug rather than ComfyUI, in which case it should be reported to the node's author."
|
34 |
+
validations:
|
35 |
+
required: true
|
36 |
+
- type: textarea
|
37 |
+
attributes:
|
38 |
+
label: Debug Logs
|
39 |
+
description: "Please copy the output from your terminal logs here."
|
40 |
+
render: powershell
|
41 |
+
validations:
|
42 |
+
required: true
|
43 |
+
- type: textarea
|
44 |
+
attributes:
|
45 |
+
label: Other
|
46 |
+
description: "Any other additional information you think might be helpful."
|
47 |
+
validations:
|
48 |
+
required: false
|
.github/ISSUE_TEMPLATE/config.yml
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
blank_issues_enabled: true
|
2 |
+
contact_links:
|
3 |
+
- name: ComfyUI Matrix Space
|
4 |
+
url: https://app.element.io/#/room/%23comfyui_space%3Amatrix.org
|
5 |
+
about: The ComfyUI Matrix Space is available for support and general discussion related to ComfyUI (Matrix is like Discord but open source).
|
6 |
+
- name: Comfy Org Discord
|
7 |
+
url: https://discord.gg/comfyorg
|
8 |
+
about: The Comfy Org Discord is available for support and general discussion related to ComfyUI.
|
.github/ISSUE_TEMPLATE/feature-request.yml
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: Feature Request
|
2 |
+
description: "You have an idea for something new you would like to see added to ComfyUI's core."
|
3 |
+
labels: [ "Feature" ]
|
4 |
+
body:
|
5 |
+
- type: markdown
|
6 |
+
attributes:
|
7 |
+
value: |
|
8 |
+
Before submitting a **Feature Request**, please ensure the following:
|
9 |
+
|
10 |
+
**1:** You are running the latest version of ComfyUI.
|
11 |
+
**2:** You have looked to make sure there is not already a feature that does what you need, and there is not already a Feature Request listed for the same idea.
|
12 |
+
**3:** This is something that makes sense to add to ComfyUI Core, and wouldn't make more sense as a custom node.
|
13 |
+
|
14 |
+
If unsure, ask on the [ComfyUI Matrix Space](https://app.element.io/#/room/%23comfyui_space%3Amatrix.org) or the [Comfy Org Discord](https://discord.gg/comfyorg) first.
|
15 |
+
- type: textarea
|
16 |
+
attributes:
|
17 |
+
label: Feature Idea
|
18 |
+
description: "Describe the feature you want to see."
|
19 |
+
validations:
|
20 |
+
required: true
|
21 |
+
- type: textarea
|
22 |
+
attributes:
|
23 |
+
label: Existing Solutions
|
24 |
+
description: "Please search through available custom nodes / extensions to see if there are existing custom solutions for this. If so, please link the options you found here as a reference."
|
25 |
+
validations:
|
26 |
+
required: false
|
27 |
+
- type: textarea
|
28 |
+
attributes:
|
29 |
+
label: Other
|
30 |
+
description: "Any other additional information you think might be helpful."
|
31 |
+
validations:
|
32 |
+
required: false
|
.github/ISSUE_TEMPLATE/user-support.yml
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: User Support
|
2 |
+
description: "Use this if you need help with something, or you're experiencing an issue."
|
3 |
+
labels: [ "User Support" ]
|
4 |
+
body:
|
5 |
+
- type: markdown
|
6 |
+
attributes:
|
7 |
+
value: |
|
8 |
+
Before submitting a **User Report** issue, please ensure the following:
|
9 |
+
|
10 |
+
**1:** You are running the latest version of ComfyUI.
|
11 |
+
**2:** You have made an effort to find public answers to your question before asking here. In other words, you googled it first, and scrolled through recent help topics.
|
12 |
+
|
13 |
+
If unsure, ask on the [ComfyUI Matrix Space](https://app.element.io/#/room/%23comfyui_space%3Amatrix.org) or the [Comfy Org Discord](https://discord.gg/comfyorg) first.
|
14 |
+
- type: textarea
|
15 |
+
attributes:
|
16 |
+
label: Your question
|
17 |
+
description: "Post your question here. Please be as detailed as possible."
|
18 |
+
validations:
|
19 |
+
required: true
|
20 |
+
- type: textarea
|
21 |
+
attributes:
|
22 |
+
label: Logs
|
23 |
+
description: "If your question relates to an issue you're experiencing, please go to `Server` -> `Logs` -> potentially set `View Type` to `Debug` as well, then copypaste all the text into here."
|
24 |
+
render: powershell
|
25 |
+
validations:
|
26 |
+
required: false
|
27 |
+
- type: textarea
|
28 |
+
attributes:
|
29 |
+
label: Other
|
30 |
+
description: "Any other additional information you think might be helpful."
|
31 |
+
validations:
|
32 |
+
required: false
|
.github/workflows/pylint.yml
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: Python Linting
|
2 |
+
|
3 |
+
on: [push, pull_request]
|
4 |
+
|
5 |
+
jobs:
|
6 |
+
pylint:
|
7 |
+
name: Run Pylint
|
8 |
+
runs-on: ubuntu-latest
|
9 |
+
|
10 |
+
steps:
|
11 |
+
- name: Checkout repository
|
12 |
+
uses: actions/checkout@v4
|
13 |
+
|
14 |
+
- name: Set up Python
|
15 |
+
uses: actions/setup-python@v2
|
16 |
+
with:
|
17 |
+
python-version: 3.x
|
18 |
+
|
19 |
+
- name: Install Pylint
|
20 |
+
run: pip install pylint
|
21 |
+
|
22 |
+
- name: Run Pylint
|
23 |
+
run: pylint --rcfile=.pylintrc $(find . -type f -name "*.py")
|
.github/workflows/stable-release.yml
ADDED
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
name: "Release Stable Version"
|
3 |
+
|
4 |
+
on:
|
5 |
+
push:
|
6 |
+
tags:
|
7 |
+
- 'v*'
|
8 |
+
|
9 |
+
jobs:
|
10 |
+
package_comfy_windows:
|
11 |
+
permissions:
|
12 |
+
contents: "write"
|
13 |
+
packages: "write"
|
14 |
+
pull-requests: "read"
|
15 |
+
runs-on: windows-latest
|
16 |
+
strategy:
|
17 |
+
matrix:
|
18 |
+
python_version: [3.11.8]
|
19 |
+
cuda_version: [121]
|
20 |
+
steps:
|
21 |
+
- name: Calculate Minor Version
|
22 |
+
shell: bash
|
23 |
+
run: |
|
24 |
+
# Extract the minor version from the Python version
|
25 |
+
MINOR_VERSION=$(echo "${{ matrix.python_version }}" | cut -d'.' -f2)
|
26 |
+
echo "MINOR_VERSION=$MINOR_VERSION" >> $GITHUB_ENV
|
27 |
+
- name: Setup Python
|
28 |
+
uses: actions/setup-python@v5
|
29 |
+
with:
|
30 |
+
python-version: ${{ matrix.python_version }}
|
31 |
+
|
32 |
+
- uses: actions/checkout@v4
|
33 |
+
with:
|
34 |
+
fetch-depth: 0
|
35 |
+
persist-credentials: false
|
36 |
+
- shell: bash
|
37 |
+
run: |
|
38 |
+
echo "@echo off
|
39 |
+
call update_comfyui.bat nopause
|
40 |
+
echo -
|
41 |
+
echo This will try to update pytorch and all python dependencies.
|
42 |
+
echo -
|
43 |
+
echo If you just want to update normally, close this and run update_comfyui.bat instead.
|
44 |
+
echo -
|
45 |
+
pause
|
46 |
+
..\python_embeded\python.exe -s -m pip install --upgrade torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu${{ matrix.cuda_version }} -r ../ComfyUI/requirements.txt pygit2
|
47 |
+
pause" > update_comfyui_and_python_dependencies.bat
|
48 |
+
|
49 |
+
python -m pip wheel --no-cache-dir torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu${{ matrix.cuda_version }} -r requirements.txt pygit2 -w ./temp_wheel_dir
|
50 |
+
python -m pip install --no-cache-dir ./temp_wheel_dir/*
|
51 |
+
echo installed basic
|
52 |
+
ls -lah temp_wheel_dir
|
53 |
+
mv temp_wheel_dir cu${{ matrix.cuda_version }}_python_deps
|
54 |
+
mv cu${{ matrix.cuda_version }}_python_deps ../
|
55 |
+
mv update_comfyui_and_python_dependencies.bat ../
|
56 |
+
cd ..
|
57 |
+
pwd
|
58 |
+
ls
|
59 |
+
|
60 |
+
cp -r ComfyUI ComfyUI_copy
|
61 |
+
curl https://www.python.org/ftp/python/${{ matrix.python_version }}/python-${{ matrix.python_version }}-embed-amd64.zip -o python_embeded.zip
|
62 |
+
unzip python_embeded.zip -d python_embeded
|
63 |
+
cd python_embeded
|
64 |
+
echo ${{ env.MINOR_VERSION }}
|
65 |
+
echo 'import site' >> ./python3${{ env.MINOR_VERSION }}._pth
|
66 |
+
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
|
67 |
+
./python.exe get-pip.py
|
68 |
+
./python.exe --version
|
69 |
+
echo "Pip version:"
|
70 |
+
./python.exe -m pip --version
|
71 |
+
|
72 |
+
set PATH=$PWD/Scripts:$PATH
|
73 |
+
echo $PATH
|
74 |
+
./python.exe -s -m pip install ../cu${{ matrix.cuda_version }}_python_deps/*
|
75 |
+
sed -i '1i../ComfyUI' ./python3${{ env.MINOR_VERSION }}._pth
|
76 |
+
cd ..
|
77 |
+
|
78 |
+
git clone https://github.com/comfyanonymous/taesd
|
79 |
+
cp taesd/*.pth ./ComfyUI_copy/models/vae_approx/
|
80 |
+
|
81 |
+
mkdir ComfyUI_windows_portable
|
82 |
+
mv python_embeded ComfyUI_windows_portable
|
83 |
+
mv ComfyUI_copy ComfyUI_windows_portable/ComfyUI
|
84 |
+
|
85 |
+
cd ComfyUI_windows_portable
|
86 |
+
|
87 |
+
mkdir update
|
88 |
+
cp -r ComfyUI/.ci/update_windows/* ./update/
|
89 |
+
cp -r ComfyUI/.ci/windows_base_files/* ./
|
90 |
+
cp ../update_comfyui_and_python_dependencies.bat ./update/
|
91 |
+
|
92 |
+
cd ..
|
93 |
+
|
94 |
+
"C:\Program Files\7-Zip\7z.exe" a -t7z -m0=lzma2 -mx=8 -mfb=64 -md=32m -ms=on -mf=BCJ2 ComfyUI_windows_portable.7z ComfyUI_windows_portable
|
95 |
+
mv ComfyUI_windows_portable.7z ComfyUI/ComfyUI_windows_portable_nvidia.7z
|
96 |
+
|
97 |
+
cd ComfyUI_windows_portable
|
98 |
+
python_embeded/python.exe -s ComfyUI/main.py --quick-test-for-ci --cpu
|
99 |
+
|
100 |
+
ls
|
101 |
+
|
102 |
+
- name: Upload binaries to release
|
103 |
+
uses: svenstaro/upload-release-action@v2
|
104 |
+
with:
|
105 |
+
repo_token: ${{ secrets.GITHUB_TOKEN }}
|
106 |
+
file: ComfyUI_windows_portable_nvidia.7z
|
107 |
+
tag: ${{ github.ref }}
|
108 |
+
overwrite: true
|
109 |
+
prerelease: true
|
110 |
+
make_latest: false
|
.github/workflows/test-browser.yml
ADDED
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This is a temporary action during frontend TS migration.
|
2 |
+
# This file should be removed after TS migration is completed.
|
3 |
+
# The browser test is here to ensure TS repo is working the same way as the
|
4 |
+
# current JS code.
|
5 |
+
# If you are adding UI feature, please sync your changes to the TS repo:
|
6 |
+
# huchenlei/ComfyUI_frontend and update test expectation files accordingly.
|
7 |
+
name: Playwright Browser Tests CI
|
8 |
+
|
9 |
+
on:
|
10 |
+
push:
|
11 |
+
branches: [ main, master ]
|
12 |
+
pull_request:
|
13 |
+
branches: [ main, master ]
|
14 |
+
|
15 |
+
jobs:
|
16 |
+
test:
|
17 |
+
runs-on: ubuntu-latest
|
18 |
+
steps:
|
19 |
+
- name: Checkout ComfyUI
|
20 |
+
uses: actions/checkout@v4
|
21 |
+
with:
|
22 |
+
repository: "comfyanonymous/ComfyUI"
|
23 |
+
path: "ComfyUI"
|
24 |
+
- name: Checkout ComfyUI_frontend
|
25 |
+
uses: actions/checkout@v4
|
26 |
+
with:
|
27 |
+
repository: "huchenlei/ComfyUI_frontend"
|
28 |
+
path: "ComfyUI_frontend"
|
29 |
+
ref: "fcc54d803e5b6a9b08a462a1d94899318c96dcbb"
|
30 |
+
- uses: actions/setup-node@v3
|
31 |
+
with:
|
32 |
+
node-version: lts/*
|
33 |
+
- uses: actions/setup-python@v4
|
34 |
+
with:
|
35 |
+
python-version: '3.10'
|
36 |
+
- name: Install requirements
|
37 |
+
run: |
|
38 |
+
python -m pip install --upgrade pip
|
39 |
+
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu
|
40 |
+
pip install -r requirements.txt
|
41 |
+
pip install wait-for-it
|
42 |
+
working-directory: ComfyUI
|
43 |
+
- name: Start ComfyUI server
|
44 |
+
run: |
|
45 |
+
python main.py --cpu 2>&1 | tee console_output.log &
|
46 |
+
wait-for-it --service 127.0.0.1:8188 -t 600
|
47 |
+
working-directory: ComfyUI
|
48 |
+
- name: Install ComfyUI_frontend dependencies
|
49 |
+
run: |
|
50 |
+
npm ci
|
51 |
+
working-directory: ComfyUI_frontend
|
52 |
+
- name: Install Playwright Browsers
|
53 |
+
run: npx playwright install --with-deps
|
54 |
+
working-directory: ComfyUI_frontend
|
55 |
+
- name: Run Playwright tests
|
56 |
+
run: npx playwright test
|
57 |
+
working-directory: ComfyUI_frontend
|
58 |
+
- name: Check for unhandled exceptions in server log
|
59 |
+
run: |
|
60 |
+
if grep -qE "Exception|Error" console_output.log; then
|
61 |
+
echo "Unhandled exception/error found in server log."
|
62 |
+
exit 1
|
63 |
+
fi
|
64 |
+
working-directory: ComfyUI
|
65 |
+
- uses: actions/upload-artifact@v4
|
66 |
+
if: always()
|
67 |
+
with:
|
68 |
+
name: playwright-report
|
69 |
+
path: ComfyUI_frontend/playwright-report/
|
70 |
+
retention-days: 30
|
71 |
+
- uses: actions/upload-artifact@v4
|
72 |
+
if: always()
|
73 |
+
with:
|
74 |
+
name: console-output
|
75 |
+
path: ComfyUI/console_output.log
|
76 |
+
retention-days: 30
|
.github/workflows/test-build.yml
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: Build package
|
2 |
+
|
3 |
+
#
|
4 |
+
# This workflow is a test of the python package build.
|
5 |
+
# Install Python dependencies across different Python versions.
|
6 |
+
#
|
7 |
+
|
8 |
+
on:
|
9 |
+
push:
|
10 |
+
paths:
|
11 |
+
- "requirements.txt"
|
12 |
+
- ".github/workflows/test-build.yml"
|
13 |
+
|
14 |
+
jobs:
|
15 |
+
build:
|
16 |
+
name: Build Test
|
17 |
+
runs-on: ubuntu-latest
|
18 |
+
strategy:
|
19 |
+
fail-fast: false
|
20 |
+
matrix:
|
21 |
+
python-version: ["3.8", "3.9", "3.10", "3.11"]
|
22 |
+
steps:
|
23 |
+
- uses: actions/checkout@v4
|
24 |
+
- name: Set up Python ${{ matrix.python-version }}
|
25 |
+
uses: actions/setup-python@v4
|
26 |
+
with:
|
27 |
+
python-version: ${{ matrix.python-version }}
|
28 |
+
- name: Install dependencies
|
29 |
+
run: |
|
30 |
+
python -m pip install --upgrade pip
|
31 |
+
pip install -r requirements.txt
|
.github/workflows/test-ui.yaml
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: Tests CI
|
2 |
+
|
3 |
+
on: [push, pull_request]
|
4 |
+
|
5 |
+
jobs:
|
6 |
+
test:
|
7 |
+
runs-on: ubuntu-latest
|
8 |
+
steps:
|
9 |
+
- uses: actions/checkout@v4
|
10 |
+
- uses: actions/setup-node@v3
|
11 |
+
with:
|
12 |
+
node-version: 18
|
13 |
+
- uses: actions/setup-python@v4
|
14 |
+
with:
|
15 |
+
python-version: '3.10'
|
16 |
+
- name: Install requirements
|
17 |
+
run: |
|
18 |
+
python -m pip install --upgrade pip
|
19 |
+
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu
|
20 |
+
pip install -r requirements.txt
|
21 |
+
- name: Run Tests
|
22 |
+
run: |
|
23 |
+
npm ci
|
24 |
+
npm run test:generate
|
25 |
+
npm test -- --verbose
|
26 |
+
working-directory: ./tests-ui
|
27 |
+
- name: Run Unit Tests
|
28 |
+
run: |
|
29 |
+
pip install -r tests-unit/requirements.txt
|
30 |
+
python -m pytest tests-unit
|
.github/workflows/windows_release_dependencies.yml
ADDED
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: "Windows Release dependencies"
|
2 |
+
|
3 |
+
on:
|
4 |
+
workflow_dispatch:
|
5 |
+
inputs:
|
6 |
+
xformers:
|
7 |
+
description: 'xformers version'
|
8 |
+
required: false
|
9 |
+
type: string
|
10 |
+
default: ""
|
11 |
+
extra_dependencies:
|
12 |
+
description: 'extra dependencies'
|
13 |
+
required: false
|
14 |
+
type: string
|
15 |
+
default: "\"numpy<2\""
|
16 |
+
cu:
|
17 |
+
description: 'cuda version'
|
18 |
+
required: true
|
19 |
+
type: string
|
20 |
+
default: "124"
|
21 |
+
|
22 |
+
python_minor:
|
23 |
+
description: 'python minor version'
|
24 |
+
required: true
|
25 |
+
type: string
|
26 |
+
default: "11"
|
27 |
+
|
28 |
+
python_patch:
|
29 |
+
description: 'python patch version'
|
30 |
+
required: true
|
31 |
+
type: string
|
32 |
+
default: "9"
|
33 |
+
# push:
|
34 |
+
# branches:
|
35 |
+
# - master
|
36 |
+
|
37 |
+
jobs:
|
38 |
+
build_dependencies:
|
39 |
+
runs-on: windows-latest
|
40 |
+
steps:
|
41 |
+
- uses: actions/checkout@v4
|
42 |
+
- uses: actions/setup-python@v5
|
43 |
+
with:
|
44 |
+
python-version: 3.${{ inputs.python_minor }}.${{ inputs.python_patch }}
|
45 |
+
|
46 |
+
- shell: bash
|
47 |
+
run: |
|
48 |
+
echo "@echo off
|
49 |
+
call update_comfyui.bat nopause
|
50 |
+
echo -
|
51 |
+
echo This will try to update pytorch and all python dependencies.
|
52 |
+
echo -
|
53 |
+
echo If you just want to update normally, close this and run update_comfyui.bat instead.
|
54 |
+
echo -
|
55 |
+
pause
|
56 |
+
..\python_embeded\python.exe -s -m pip install --upgrade torch torchvision torchaudio ${{ inputs.xformers }} --extra-index-url https://download.pytorch.org/whl/cu${{ inputs.cu }} -r ../ComfyUI/requirements.txt pygit2
|
57 |
+
pause" > update_comfyui_and_python_dependencies.bat
|
58 |
+
|
59 |
+
python -m pip wheel --no-cache-dir torch torchvision torchaudio ${{ inputs.xformers }} ${{ inputs.extra_dependencies }} --extra-index-url https://download.pytorch.org/whl/cu${{ inputs.cu }} -r requirements.txt pygit2 -w ./temp_wheel_dir
|
60 |
+
python -m pip install --no-cache-dir ./temp_wheel_dir/*
|
61 |
+
echo installed basic
|
62 |
+
ls -lah temp_wheel_dir
|
63 |
+
mv temp_wheel_dir cu${{ inputs.cu }}_python_deps
|
64 |
+
tar cf cu${{ inputs.cu }}_python_deps.tar cu${{ inputs.cu }}_python_deps
|
65 |
+
|
66 |
+
- uses: actions/cache/save@v4
|
67 |
+
with:
|
68 |
+
path: |
|
69 |
+
cu${{ inputs.cu }}_python_deps.tar
|
70 |
+
update_comfyui_and_python_dependencies.bat
|
71 |
+
key: ${{ runner.os }}-build-cu${{ inputs.cu }}-${{ inputs.python_minor }}
|
.github/workflows/windows_release_nightly_pytorch.yml
ADDED
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: "Windows Release Nightly pytorch"
|
2 |
+
|
3 |
+
on:
|
4 |
+
workflow_dispatch:
|
5 |
+
inputs:
|
6 |
+
cu:
|
7 |
+
description: 'cuda version'
|
8 |
+
required: true
|
9 |
+
type: string
|
10 |
+
default: "124"
|
11 |
+
|
12 |
+
python_minor:
|
13 |
+
description: 'python minor version'
|
14 |
+
required: true
|
15 |
+
type: string
|
16 |
+
default: "12"
|
17 |
+
|
18 |
+
python_patch:
|
19 |
+
description: 'python patch version'
|
20 |
+
required: true
|
21 |
+
type: string
|
22 |
+
default: "4"
|
23 |
+
# push:
|
24 |
+
# branches:
|
25 |
+
# - master
|
26 |
+
|
27 |
+
jobs:
|
28 |
+
build:
|
29 |
+
permissions:
|
30 |
+
contents: "write"
|
31 |
+
packages: "write"
|
32 |
+
pull-requests: "read"
|
33 |
+
runs-on: windows-latest
|
34 |
+
steps:
|
35 |
+
- uses: actions/checkout@v4
|
36 |
+
with:
|
37 |
+
fetch-depth: 0
|
38 |
+
persist-credentials: false
|
39 |
+
- uses: actions/setup-python@v5
|
40 |
+
with:
|
41 |
+
python-version: 3.${{ inputs.python_minor }}.${{ inputs.python_patch }}
|
42 |
+
- shell: bash
|
43 |
+
run: |
|
44 |
+
cd ..
|
45 |
+
cp -r ComfyUI ComfyUI_copy
|
46 |
+
curl https://www.python.org/ftp/python/3.${{ inputs.python_minor }}.${{ inputs.python_patch }}/python-3.${{ inputs.python_minor }}.${{ inputs.python_patch }}-embed-amd64.zip -o python_embeded.zip
|
47 |
+
unzip python_embeded.zip -d python_embeded
|
48 |
+
cd python_embeded
|
49 |
+
echo 'import site' >> ./python3${{ inputs.python_minor }}._pth
|
50 |
+
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
|
51 |
+
./python.exe get-pip.py
|
52 |
+
python -m pip wheel torch torchvision torchaudio --pre --extra-index-url https://download.pytorch.org/whl/nightly/cu${{ inputs.cu }} -r ../ComfyUI/requirements.txt pygit2 -w ../temp_wheel_dir
|
53 |
+
ls ../temp_wheel_dir
|
54 |
+
./python.exe -s -m pip install --pre ../temp_wheel_dir/*
|
55 |
+
sed -i '1i../ComfyUI' ./python3${{ inputs.python_minor }}._pth
|
56 |
+
cd ..
|
57 |
+
|
58 |
+
git clone https://github.com/comfyanonymous/taesd
|
59 |
+
cp taesd/*.pth ./ComfyUI_copy/models/vae_approx/
|
60 |
+
|
61 |
+
mkdir ComfyUI_windows_portable_nightly_pytorch
|
62 |
+
mv python_embeded ComfyUI_windows_portable_nightly_pytorch
|
63 |
+
mv ComfyUI_copy ComfyUI_windows_portable_nightly_pytorch/ComfyUI
|
64 |
+
|
65 |
+
cd ComfyUI_windows_portable_nightly_pytorch
|
66 |
+
|
67 |
+
mkdir update
|
68 |
+
cp -r ComfyUI/.ci/update_windows/* ./update/
|
69 |
+
cp -r ComfyUI/.ci/windows_base_files/* ./
|
70 |
+
|
71 |
+
echo "call update_comfyui.bat nopause
|
72 |
+
..\python_embeded\python.exe -s -m pip install --upgrade --pre torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/nightly/cu${{ inputs.cu }} -r ../ComfyUI/requirements.txt pygit2
|
73 |
+
pause" > ./update/update_comfyui_and_python_dependencies.bat
|
74 |
+
cd ..
|
75 |
+
|
76 |
+
"C:\Program Files\7-Zip\7z.exe" a -t7z -m0=lzma2 -mx=8 -mfb=64 -md=32m -ms=on -mf=BCJ2 ComfyUI_windows_portable_nightly_pytorch.7z ComfyUI_windows_portable_nightly_pytorch
|
77 |
+
mv ComfyUI_windows_portable_nightly_pytorch.7z ComfyUI/ComfyUI_windows_portable_nvidia_or_cpu_nightly_pytorch.7z
|
78 |
+
|
79 |
+
cd ComfyUI_windows_portable_nightly_pytorch
|
80 |
+
python_embeded/python.exe -s ComfyUI/main.py --quick-test-for-ci --cpu
|
81 |
+
|
82 |
+
ls
|
83 |
+
|
84 |
+
- name: Upload binaries to release
|
85 |
+
uses: svenstaro/upload-release-action@v2
|
86 |
+
with:
|
87 |
+
repo_token: ${{ secrets.GITHUB_TOKEN }}
|
88 |
+
file: ComfyUI_windows_portable_nvidia_or_cpu_nightly_pytorch.7z
|
89 |
+
tag: "latest"
|
90 |
+
overwrite: true
|
.github/workflows/windows_release_package.yml
ADDED
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: "Windows Release packaging"
|
2 |
+
|
3 |
+
on:
|
4 |
+
workflow_dispatch:
|
5 |
+
inputs:
|
6 |
+
cu:
|
7 |
+
description: 'cuda version'
|
8 |
+
required: true
|
9 |
+
type: string
|
10 |
+
default: "124"
|
11 |
+
|
12 |
+
python_minor:
|
13 |
+
description: 'python minor version'
|
14 |
+
required: true
|
15 |
+
type: string
|
16 |
+
default: "11"
|
17 |
+
|
18 |
+
python_patch:
|
19 |
+
description: 'python patch version'
|
20 |
+
required: true
|
21 |
+
type: string
|
22 |
+
default: "9"
|
23 |
+
# push:
|
24 |
+
# branches:
|
25 |
+
# - master
|
26 |
+
|
27 |
+
jobs:
|
28 |
+
package_comfyui:
|
29 |
+
permissions:
|
30 |
+
contents: "write"
|
31 |
+
packages: "write"
|
32 |
+
pull-requests: "read"
|
33 |
+
runs-on: windows-latest
|
34 |
+
steps:
|
35 |
+
- uses: actions/cache/restore@v4
|
36 |
+
id: cache
|
37 |
+
with:
|
38 |
+
path: |
|
39 |
+
cu${{ inputs.cu }}_python_deps.tar
|
40 |
+
update_comfyui_and_python_dependencies.bat
|
41 |
+
key: ${{ runner.os }}-build-cu${{ inputs.cu }}-${{ inputs.python_minor }}
|
42 |
+
- shell: bash
|
43 |
+
run: |
|
44 |
+
mv cu${{ inputs.cu }}_python_deps.tar ../
|
45 |
+
mv update_comfyui_and_python_dependencies.bat ../
|
46 |
+
cd ..
|
47 |
+
tar xf cu${{ inputs.cu }}_python_deps.tar
|
48 |
+
pwd
|
49 |
+
ls
|
50 |
+
|
51 |
+
- uses: actions/checkout@v4
|
52 |
+
with:
|
53 |
+
fetch-depth: 0
|
54 |
+
persist-credentials: false
|
55 |
+
- shell: bash
|
56 |
+
run: |
|
57 |
+
cd ..
|
58 |
+
cp -r ComfyUI ComfyUI_copy
|
59 |
+
curl https://www.python.org/ftp/python/3.${{ inputs.python_minor }}.${{ inputs.python_patch }}/python-3.${{ inputs.python_minor }}.${{ inputs.python_patch }}-embed-amd64.zip -o python_embeded.zip
|
60 |
+
unzip python_embeded.zip -d python_embeded
|
61 |
+
cd python_embeded
|
62 |
+
echo 'import site' >> ./python3${{ inputs.python_minor }}._pth
|
63 |
+
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
|
64 |
+
./python.exe get-pip.py
|
65 |
+
./python.exe -s -m pip install ../cu${{ inputs.cu }}_python_deps/*
|
66 |
+
sed -i '1i../ComfyUI' ./python3${{ inputs.python_minor }}._pth
|
67 |
+
cd ..
|
68 |
+
|
69 |
+
git clone https://github.com/comfyanonymous/taesd
|
70 |
+
cp taesd/*.pth ./ComfyUI_copy/models/vae_approx/
|
71 |
+
|
72 |
+
mkdir ComfyUI_windows_portable
|
73 |
+
mv python_embeded ComfyUI_windows_portable
|
74 |
+
mv ComfyUI_copy ComfyUI_windows_portable/ComfyUI
|
75 |
+
|
76 |
+
cd ComfyUI_windows_portable
|
77 |
+
|
78 |
+
mkdir update
|
79 |
+
cp -r ComfyUI/.ci/update_windows/* ./update/
|
80 |
+
cp -r ComfyUI/.ci/windows_base_files/* ./
|
81 |
+
cp ../update_comfyui_and_python_dependencies.bat ./update/
|
82 |
+
|
83 |
+
cd ..
|
84 |
+
|
85 |
+
"C:\Program Files\7-Zip\7z.exe" a -t7z -m0=lzma2 -mx=8 -mfb=64 -md=32m -ms=on -mf=BCJ2 ComfyUI_windows_portable.7z ComfyUI_windows_portable
|
86 |
+
mv ComfyUI_windows_portable.7z ComfyUI/new_ComfyUI_windows_portable_nvidia_cu${{ inputs.cu }}_or_cpu.7z
|
87 |
+
|
88 |
+
cd ComfyUI_windows_portable
|
89 |
+
python_embeded/python.exe -s ComfyUI/main.py --quick-test-for-ci --cpu
|
90 |
+
|
91 |
+
ls
|
92 |
+
|
93 |
+
- name: Upload binaries to release
|
94 |
+
uses: svenstaro/upload-release-action@v2
|
95 |
+
with:
|
96 |
+
repo_token: ${{ secrets.GITHUB_TOKEN }}
|
97 |
+
file: new_ComfyUI_windows_portable_nvidia_cu${{ inputs.cu }}_or_cpu.7z
|
98 |
+
tag: "latest"
|
99 |
+
overwrite: true
|
100 |
+
|
.gitignore
ADDED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
venv/
|
2 |
+
*/venv/
|
3 |
+
__pycache__/
|
4 |
+
*.so
|
5 |
+
*.log
|
6 |
+
.DS_Store
|
7 |
+
*.pyc
|
8 |
+
*.map
|
9 |
+
*.bin
|
10 |
+
*.safetensors
|
11 |
+
*.ttf
|
12 |
+
*.png
|
13 |
+
custom_nodes/ComfyUI-KJNodes/intrinsic_loras/
|
14 |
+
custom_nodes/ComfyUI_LayerStyle_Advance/font/
|
15 |
+
custom_nodes/ComfyUI_LayerStyle_Advance/workflow/
|
16 |
+
custom_nodes/rgthree-comfy/docs/
|
17 |
+
output/
|
18 |
+
temp/
|
19 |
+
/models/
|
20 |
+
|
21 |
+
|
22 |
+
__pycache__/
|
23 |
+
*.py[cod]
|
24 |
+
/output/
|
25 |
+
/input/
|
26 |
+
!/input/example.png
|
27 |
+
/models/
|
28 |
+
/temp/
|
29 |
+
/custom_nodes/
|
30 |
+
!custom_nodes/example_node.py.example
|
31 |
+
extra_model_paths.yaml
|
32 |
+
/.vs
|
33 |
+
.vscode/
|
34 |
+
.idea/
|
35 |
+
venv/
|
36 |
+
.venv/
|
37 |
+
/web/extensions/*
|
38 |
+
!/web/extensions/logging.js.example
|
39 |
+
!/web/extensions/core/
|
40 |
+
/tests-ui/data/object_info.json
|
41 |
+
/user/
|
42 |
+
*.log
|
43 |
+
web_custom_versions/
|
44 |
+
.DS_Store
|
.gradio/certificate.pem
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
-----BEGIN CERTIFICATE-----
|
2 |
+
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
|
3 |
+
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
|
4 |
+
cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
|
5 |
+
WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
|
6 |
+
ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
|
7 |
+
MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
|
8 |
+
h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+
|
9 |
+
0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U
|
10 |
+
A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW
|
11 |
+
T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH
|
12 |
+
B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC
|
13 |
+
B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv
|
14 |
+
KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn
|
15 |
+
OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn
|
16 |
+
jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw
|
17 |
+
qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI
|
18 |
+
rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV
|
19 |
+
HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq
|
20 |
+
hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL
|
21 |
+
ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ
|
22 |
+
3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK
|
23 |
+
NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5
|
24 |
+
ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur
|
25 |
+
TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC
|
26 |
+
jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc
|
27 |
+
oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq
|
28 |
+
4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
|
29 |
+
mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
|
30 |
+
emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
|
31 |
+
-----END CERTIFICATE-----
|
.pylintrc
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
[MESSAGES CONTROL]
|
2 |
+
disable=all
|
3 |
+
enable=eval-used
|
CODEOWNERS
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
* @comfyanonymous
|
CONTRIBUTING.md
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Contributing to ComfyUI
|
2 |
+
|
3 |
+
Welcome, and thank you for your interest in contributing to ComfyUI!
|
4 |
+
|
5 |
+
There are several ways in which you can contribute, beyond writing code. The goal of this document is to provide a high-level overview of how you can get involved.
|
6 |
+
|
7 |
+
## Asking Questions
|
8 |
+
|
9 |
+
Have a question? Instead of opening an issue, please ask on [Discord](https://comfy.org/discord) or [Matrix](https://app.element.io/#/room/%23comfyui_space%3Amatrix.org) channels. Our team and the community will help you.
|
10 |
+
|
11 |
+
## Providing Feedback
|
12 |
+
|
13 |
+
Your comments and feedback are welcome, and the development team is available via a handful of different channels.
|
14 |
+
|
15 |
+
See the `#bug-report`, `#feature-request` and `#feedback` channels on Discord.
|
16 |
+
|
17 |
+
## Reporting Issues
|
18 |
+
|
19 |
+
Have you identified a reproducible problem in ComfyUI? Do you have a feature request? We want to hear about it! Here's how you can report your issue as effectively as possible.
|
20 |
+
|
21 |
+
|
22 |
+
### Look For an Existing Issue
|
23 |
+
|
24 |
+
Before you create a new issue, please do a search in [open issues](https://github.com/comfyanonymous/ComfyUI/issues) to see if the issue or feature request has already been filed.
|
25 |
+
|
26 |
+
If you find your issue already exists, make relevant comments and add your [reaction](https://github.com/blog/2119-add-reactions-to-pull-requests-issues-and-comments). Use a reaction in place of a "+1" comment:
|
27 |
+
|
28 |
+
* 👍 - upvote
|
29 |
+
* 👎 - downvote
|
30 |
+
|
31 |
+
If you cannot find an existing issue that describes your bug or feature, create a new issue. We have an issue template in place to organize new issues.
|
32 |
+
|
33 |
+
|
34 |
+
### Creating Pull Requests
|
35 |
+
|
36 |
+
* Please refer to the article on [creating pull requests](https://github.com/comfyanonymous/ComfyUI/wiki/How-to-Contribute-Code) and contributing to this project.
|
37 |
+
|
38 |
+
|
39 |
+
## Thank You
|
40 |
+
|
41 |
+
Your contributions to open source, large or small, make great projects like this possible. Thank you for taking the time to contribute.
|
LICENSE
ADDED
@@ -0,0 +1,674 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
GNU GENERAL PUBLIC LICENSE
|
2 |
+
Version 3, 29 June 2007
|
3 |
+
|
4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
5 |
+
Everyone is permitted to copy and distribute verbatim copies
|
6 |
+
of this license document, but changing it is not allowed.
|
7 |
+
|
8 |
+
Preamble
|
9 |
+
|
10 |
+
The GNU General Public License is a free, copyleft license for
|
11 |
+
software and other kinds of works.
|
12 |
+
|
13 |
+
The licenses for most software and other practical works are designed
|
14 |
+
to take away your freedom to share and change the works. By contrast,
|
15 |
+
the GNU General Public License is intended to guarantee your freedom to
|
16 |
+
share and change all versions of a program--to make sure it remains free
|
17 |
+
software for all its users. We, the Free Software Foundation, use the
|
18 |
+
GNU General Public License for most of our software; it applies also to
|
19 |
+
any other work released this way by its authors. You can apply it to
|
20 |
+
your programs, too.
|
21 |
+
|
22 |
+
When we speak of free software, we are referring to freedom, not
|
23 |
+
price. Our General Public Licenses are designed to make sure that you
|
24 |
+
have the freedom to distribute copies of free software (and charge for
|
25 |
+
them if you wish), that you receive source code or can get it if you
|
26 |
+
want it, that you can change the software or use pieces of it in new
|
27 |
+
free programs, and that you know you can do these things.
|
28 |
+
|
29 |
+
To protect your rights, we need to prevent others from denying you
|
30 |
+
these rights or asking you to surrender the rights. Therefore, you have
|
31 |
+
certain responsibilities if you distribute copies of the software, or if
|
32 |
+
you modify it: responsibilities to respect the freedom of others.
|
33 |
+
|
34 |
+
For example, if you distribute copies of such a program, whether
|
35 |
+
gratis or for a fee, you must pass on to the recipients the same
|
36 |
+
freedoms that you received. You must make sure that they, too, receive
|
37 |
+
or can get the source code. And you must show them these terms so they
|
38 |
+
know their rights.
|
39 |
+
|
40 |
+
Developers that use the GNU GPL protect your rights with two steps:
|
41 |
+
(1) assert copyright on the software, and (2) offer you this License
|
42 |
+
giving you legal permission to copy, distribute and/or modify it.
|
43 |
+
|
44 |
+
For the developers' and authors' protection, the GPL clearly explains
|
45 |
+
that there is no warranty for this free software. For both users' and
|
46 |
+
authors' sake, the GPL requires that modified versions be marked as
|
47 |
+
changed, so that their problems will not be attributed erroneously to
|
48 |
+
authors of previous versions.
|
49 |
+
|
50 |
+
Some devices are designed to deny users access to install or run
|
51 |
+
modified versions of the software inside them, although the manufacturer
|
52 |
+
can do so. This is fundamentally incompatible with the aim of
|
53 |
+
protecting users' freedom to change the software. The systematic
|
54 |
+
pattern of such abuse occurs in the area of products for individuals to
|
55 |
+
use, which is precisely where it is most unacceptable. Therefore, we
|
56 |
+
have designed this version of the GPL to prohibit the practice for those
|
57 |
+
products. If such problems arise substantially in other domains, we
|
58 |
+
stand ready to extend this provision to those domains in future versions
|
59 |
+
of the GPL, as needed to protect the freedom of users.
|
60 |
+
|
61 |
+
Finally, every program is threatened constantly by software patents.
|
62 |
+
States should not allow patents to restrict development and use of
|
63 |
+
software on general-purpose computers, but in those that do, we wish to
|
64 |
+
avoid the special danger that patents applied to a free program could
|
65 |
+
make it effectively proprietary. To prevent this, the GPL assures that
|
66 |
+
patents cannot be used to render the program non-free.
|
67 |
+
|
68 |
+
The precise terms and conditions for copying, distribution and
|
69 |
+
modification follow.
|
70 |
+
|
71 |
+
TERMS AND CONDITIONS
|
72 |
+
|
73 |
+
0. Definitions.
|
74 |
+
|
75 |
+
"This License" refers to version 3 of the GNU General Public License.
|
76 |
+
|
77 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
78 |
+
works, such as semiconductor masks.
|
79 |
+
|
80 |
+
"The Program" refers to any copyrightable work licensed under this
|
81 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
82 |
+
"recipients" may be individuals or organizations.
|
83 |
+
|
84 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
85 |
+
in a fashion requiring copyright permission, other than the making of an
|
86 |
+
exact copy. The resulting work is called a "modified version" of the
|
87 |
+
earlier work or a work "based on" the earlier work.
|
88 |
+
|
89 |
+
A "covered work" means either the unmodified Program or a work based
|
90 |
+
on the Program.
|
91 |
+
|
92 |
+
To "propagate" a work means to do anything with it that, without
|
93 |
+
permission, would make you directly or secondarily liable for
|
94 |
+
infringement under applicable copyright law, except executing it on a
|
95 |
+
computer or modifying a private copy. Propagation includes copying,
|
96 |
+
distribution (with or without modification), making available to the
|
97 |
+
public, and in some countries other activities as well.
|
98 |
+
|
99 |
+
To "convey" a work means any kind of propagation that enables other
|
100 |
+
parties to make or receive copies. Mere interaction with a user through
|
101 |
+
a computer network, with no transfer of a copy, is not conveying.
|
102 |
+
|
103 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
104 |
+
to the extent that it includes a convenient and prominently visible
|
105 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
106 |
+
tells the user that there is no warranty for the work (except to the
|
107 |
+
extent that warranties are provided), that licensees may convey the
|
108 |
+
work under this License, and how to view a copy of this License. If
|
109 |
+
the interface presents a list of user commands or options, such as a
|
110 |
+
menu, a prominent item in the list meets this criterion.
|
111 |
+
|
112 |
+
1. Source Code.
|
113 |
+
|
114 |
+
The "source code" for a work means the preferred form of the work
|
115 |
+
for making modifications to it. "Object code" means any non-source
|
116 |
+
form of a work.
|
117 |
+
|
118 |
+
A "Standard Interface" means an interface that either is an official
|
119 |
+
standard defined by a recognized standards body, or, in the case of
|
120 |
+
interfaces specified for a particular programming language, one that
|
121 |
+
is widely used among developers working in that language.
|
122 |
+
|
123 |
+
The "System Libraries" of an executable work include anything, other
|
124 |
+
than the work as a whole, that (a) is included in the normal form of
|
125 |
+
packaging a Major Component, but which is not part of that Major
|
126 |
+
Component, and (b) serves only to enable use of the work with that
|
127 |
+
Major Component, or to implement a Standard Interface for which an
|
128 |
+
implementation is available to the public in source code form. A
|
129 |
+
"Major Component", in this context, means a major essential component
|
130 |
+
(kernel, window system, and so on) of the specific operating system
|
131 |
+
(if any) on which the executable work runs, or a compiler used to
|
132 |
+
produce the work, or an object code interpreter used to run it.
|
133 |
+
|
134 |
+
The "Corresponding Source" for a work in object code form means all
|
135 |
+
the source code needed to generate, install, and (for an executable
|
136 |
+
work) run the object code and to modify the work, including scripts to
|
137 |
+
control those activities. However, it does not include the work's
|
138 |
+
System Libraries, or general-purpose tools or generally available free
|
139 |
+
programs which are used unmodified in performing those activities but
|
140 |
+
which are not part of the work. For example, Corresponding Source
|
141 |
+
includes interface definition files associated with source files for
|
142 |
+
the work, and the source code for shared libraries and dynamically
|
143 |
+
linked subprograms that the work is specifically designed to require,
|
144 |
+
such as by intimate data communication or control flow between those
|
145 |
+
subprograms and other parts of the work.
|
146 |
+
|
147 |
+
The Corresponding Source need not include anything that users
|
148 |
+
can regenerate automatically from other parts of the Corresponding
|
149 |
+
Source.
|
150 |
+
|
151 |
+
The Corresponding Source for a work in source code form is that
|
152 |
+
same work.
|
153 |
+
|
154 |
+
2. Basic Permissions.
|
155 |
+
|
156 |
+
All rights granted under this License are granted for the term of
|
157 |
+
copyright on the Program, and are irrevocable provided the stated
|
158 |
+
conditions are met. This License explicitly affirms your unlimited
|
159 |
+
permission to run the unmodified Program. The output from running a
|
160 |
+
covered work is covered by this License only if the output, given its
|
161 |
+
content, constitutes a covered work. This License acknowledges your
|
162 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
163 |
+
|
164 |
+
You may make, run and propagate covered works that you do not
|
165 |
+
convey, without conditions so long as your license otherwise remains
|
166 |
+
in force. You may convey covered works to others for the sole purpose
|
167 |
+
of having them make modifications exclusively for you, or provide you
|
168 |
+
with facilities for running those works, provided that you comply with
|
169 |
+
the terms of this License in conveying all material for which you do
|
170 |
+
not control copyright. Those thus making or running the covered works
|
171 |
+
for you must do so exclusively on your behalf, under your direction
|
172 |
+
and control, on terms that prohibit them from making any copies of
|
173 |
+
your copyrighted material outside their relationship with you.
|
174 |
+
|
175 |
+
Conveying under any other circumstances is permitted solely under
|
176 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
177 |
+
makes it unnecessary.
|
178 |
+
|
179 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
180 |
+
|
181 |
+
No covered work shall be deemed part of an effective technological
|
182 |
+
measure under any applicable law fulfilling obligations under article
|
183 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
184 |
+
similar laws prohibiting or restricting circumvention of such
|
185 |
+
measures.
|
186 |
+
|
187 |
+
When you convey a covered work, you waive any legal power to forbid
|
188 |
+
circumvention of technological measures to the extent such circumvention
|
189 |
+
is effected by exercising rights under this License with respect to
|
190 |
+
the covered work, and you disclaim any intention to limit operation or
|
191 |
+
modification of the work as a means of enforcing, against the work's
|
192 |
+
users, your or third parties' legal rights to forbid circumvention of
|
193 |
+
technological measures.
|
194 |
+
|
195 |
+
4. Conveying Verbatim Copies.
|
196 |
+
|
197 |
+
You may convey verbatim copies of the Program's source code as you
|
198 |
+
receive it, in any medium, provided that you conspicuously and
|
199 |
+
appropriately publish on each copy an appropriate copyright notice;
|
200 |
+
keep intact all notices stating that this License and any
|
201 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
202 |
+
keep intact all notices of the absence of any warranty; and give all
|
203 |
+
recipients a copy of this License along with the Program.
|
204 |
+
|
205 |
+
You may charge any price or no price for each copy that you convey,
|
206 |
+
and you may offer support or warranty protection for a fee.
|
207 |
+
|
208 |
+
5. Conveying Modified Source Versions.
|
209 |
+
|
210 |
+
You may convey a work based on the Program, or the modifications to
|
211 |
+
produce it from the Program, in the form of source code under the
|
212 |
+
terms of section 4, provided that you also meet all of these conditions:
|
213 |
+
|
214 |
+
a) The work must carry prominent notices stating that you modified
|
215 |
+
it, and giving a relevant date.
|
216 |
+
|
217 |
+
b) The work must carry prominent notices stating that it is
|
218 |
+
released under this License and any conditions added under section
|
219 |
+
7. This requirement modifies the requirement in section 4 to
|
220 |
+
"keep intact all notices".
|
221 |
+
|
222 |
+
c) You must license the entire work, as a whole, under this
|
223 |
+
License to anyone who comes into possession of a copy. This
|
224 |
+
License will therefore apply, along with any applicable section 7
|
225 |
+
additional terms, to the whole of the work, and all its parts,
|
226 |
+
regardless of how they are packaged. This License gives no
|
227 |
+
permission to license the work in any other way, but it does not
|
228 |
+
invalidate such permission if you have separately received it.
|
229 |
+
|
230 |
+
d) If the work has interactive user interfaces, each must display
|
231 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
232 |
+
interfaces that do not display Appropriate Legal Notices, your
|
233 |
+
work need not make them do so.
|
234 |
+
|
235 |
+
A compilation of a covered work with other separate and independent
|
236 |
+
works, which are not by their nature extensions of the covered work,
|
237 |
+
and which are not combined with it such as to form a larger program,
|
238 |
+
in or on a volume of a storage or distribution medium, is called an
|
239 |
+
"aggregate" if the compilation and its resulting copyright are not
|
240 |
+
used to limit the access or legal rights of the compilation's users
|
241 |
+
beyond what the individual works permit. Inclusion of a covered work
|
242 |
+
in an aggregate does not cause this License to apply to the other
|
243 |
+
parts of the aggregate.
|
244 |
+
|
245 |
+
6. Conveying Non-Source Forms.
|
246 |
+
|
247 |
+
You may convey a covered work in object code form under the terms
|
248 |
+
of sections 4 and 5, provided that you also convey the
|
249 |
+
machine-readable Corresponding Source under the terms of this License,
|
250 |
+
in one of these ways:
|
251 |
+
|
252 |
+
a) Convey the object code in, or embodied in, a physical product
|
253 |
+
(including a physical distribution medium), accompanied by the
|
254 |
+
Corresponding Source fixed on a durable physical medium
|
255 |
+
customarily used for software interchange.
|
256 |
+
|
257 |
+
b) Convey the object code in, or embodied in, a physical product
|
258 |
+
(including a physical distribution medium), accompanied by a
|
259 |
+
written offer, valid for at least three years and valid for as
|
260 |
+
long as you offer spare parts or customer support for that product
|
261 |
+
model, to give anyone who possesses the object code either (1) a
|
262 |
+
copy of the Corresponding Source for all the software in the
|
263 |
+
product that is covered by this License, on a durable physical
|
264 |
+
medium customarily used for software interchange, for a price no
|
265 |
+
more than your reasonable cost of physically performing this
|
266 |
+
conveying of source, or (2) access to copy the
|
267 |
+
Corresponding Source from a network server at no charge.
|
268 |
+
|
269 |
+
c) Convey individual copies of the object code with a copy of the
|
270 |
+
written offer to provide the Corresponding Source. This
|
271 |
+
alternative is allowed only occasionally and noncommercially, and
|
272 |
+
only if you received the object code with such an offer, in accord
|
273 |
+
with subsection 6b.
|
274 |
+
|
275 |
+
d) Convey the object code by offering access from a designated
|
276 |
+
place (gratis or for a charge), and offer equivalent access to the
|
277 |
+
Corresponding Source in the same way through the same place at no
|
278 |
+
further charge. You need not require recipients to copy the
|
279 |
+
Corresponding Source along with the object code. If the place to
|
280 |
+
copy the object code is a network server, the Corresponding Source
|
281 |
+
may be on a different server (operated by you or a third party)
|
282 |
+
that supports equivalent copying facilities, provided you maintain
|
283 |
+
clear directions next to the object code saying where to find the
|
284 |
+
Corresponding Source. Regardless of what server hosts the
|
285 |
+
Corresponding Source, you remain obligated to ensure that it is
|
286 |
+
available for as long as needed to satisfy these requirements.
|
287 |
+
|
288 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
289 |
+
you inform other peers where the object code and Corresponding
|
290 |
+
Source of the work are being offered to the general public at no
|
291 |
+
charge under subsection 6d.
|
292 |
+
|
293 |
+
A separable portion of the object code, whose source code is excluded
|
294 |
+
from the Corresponding Source as a System Library, need not be
|
295 |
+
included in conveying the object code work.
|
296 |
+
|
297 |
+
A "User Product" is either (1) a "consumer product", which means any
|
298 |
+
tangible personal property which is normally used for personal, family,
|
299 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
300 |
+
into a dwelling. In determining whether a product is a consumer product,
|
301 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
302 |
+
product received by a particular user, "normally used" refers to a
|
303 |
+
typical or common use of that class of product, regardless of the status
|
304 |
+
of the particular user or of the way in which the particular user
|
305 |
+
actually uses, or expects or is expected to use, the product. A product
|
306 |
+
is a consumer product regardless of whether the product has substantial
|
307 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
308 |
+
the only significant mode of use of the product.
|
309 |
+
|
310 |
+
"Installation Information" for a User Product means any methods,
|
311 |
+
procedures, authorization keys, or other information required to install
|
312 |
+
and execute modified versions of a covered work in that User Product from
|
313 |
+
a modified version of its Corresponding Source. The information must
|
314 |
+
suffice to ensure that the continued functioning of the modified object
|
315 |
+
code is in no case prevented or interfered with solely because
|
316 |
+
modification has been made.
|
317 |
+
|
318 |
+
If you convey an object code work under this section in, or with, or
|
319 |
+
specifically for use in, a User Product, and the conveying occurs as
|
320 |
+
part of a transaction in which the right of possession and use of the
|
321 |
+
User Product is transferred to the recipient in perpetuity or for a
|
322 |
+
fixed term (regardless of how the transaction is characterized), the
|
323 |
+
Corresponding Source conveyed under this section must be accompanied
|
324 |
+
by the Installation Information. But this requirement does not apply
|
325 |
+
if neither you nor any third party retains the ability to install
|
326 |
+
modified object code on the User Product (for example, the work has
|
327 |
+
been installed in ROM).
|
328 |
+
|
329 |
+
The requirement to provide Installation Information does not include a
|
330 |
+
requirement to continue to provide support service, warranty, or updates
|
331 |
+
for a work that has been modified or installed by the recipient, or for
|
332 |
+
the User Product in which it has been modified or installed. Access to a
|
333 |
+
network may be denied when the modification itself materially and
|
334 |
+
adversely affects the operation of the network or violates the rules and
|
335 |
+
protocols for communication across the network.
|
336 |
+
|
337 |
+
Corresponding Source conveyed, and Installation Information provided,
|
338 |
+
in accord with this section must be in a format that is publicly
|
339 |
+
documented (and with an implementation available to the public in
|
340 |
+
source code form), and must require no special password or key for
|
341 |
+
unpacking, reading or copying.
|
342 |
+
|
343 |
+
7. Additional Terms.
|
344 |
+
|
345 |
+
"Additional permissions" are terms that supplement the terms of this
|
346 |
+
License by making exceptions from one or more of its conditions.
|
347 |
+
Additional permissions that are applicable to the entire Program shall
|
348 |
+
be treated as though they were included in this License, to the extent
|
349 |
+
that they are valid under applicable law. If additional permissions
|
350 |
+
apply only to part of the Program, that part may be used separately
|
351 |
+
under those permissions, but the entire Program remains governed by
|
352 |
+
this License without regard to the additional permissions.
|
353 |
+
|
354 |
+
When you convey a copy of a covered work, you may at your option
|
355 |
+
remove any additional permissions from that copy, or from any part of
|
356 |
+
it. (Additional permissions may be written to require their own
|
357 |
+
removal in certain cases when you modify the work.) You may place
|
358 |
+
additional permissions on material, added by you to a covered work,
|
359 |
+
for which you have or can give appropriate copyright permission.
|
360 |
+
|
361 |
+
Notwithstanding any other provision of this License, for material you
|
362 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
363 |
+
that material) supplement the terms of this License with terms:
|
364 |
+
|
365 |
+
a) Disclaiming warranty or limiting liability differently from the
|
366 |
+
terms of sections 15 and 16 of this License; or
|
367 |
+
|
368 |
+
b) Requiring preservation of specified reasonable legal notices or
|
369 |
+
author attributions in that material or in the Appropriate Legal
|
370 |
+
Notices displayed by works containing it; or
|
371 |
+
|
372 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
373 |
+
requiring that modified versions of such material be marked in
|
374 |
+
reasonable ways as different from the original version; or
|
375 |
+
|
376 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
377 |
+
authors of the material; or
|
378 |
+
|
379 |
+
e) Declining to grant rights under trademark law for use of some
|
380 |
+
trade names, trademarks, or service marks; or
|
381 |
+
|
382 |
+
f) Requiring indemnification of licensors and authors of that
|
383 |
+
material by anyone who conveys the material (or modified versions of
|
384 |
+
it) with contractual assumptions of liability to the recipient, for
|
385 |
+
any liability that these contractual assumptions directly impose on
|
386 |
+
those licensors and authors.
|
387 |
+
|
388 |
+
All other non-permissive additional terms are considered "further
|
389 |
+
restrictions" within the meaning of section 10. If the Program as you
|
390 |
+
received it, or any part of it, contains a notice stating that it is
|
391 |
+
governed by this License along with a term that is a further
|
392 |
+
restriction, you may remove that term. If a license document contains
|
393 |
+
a further restriction but permits relicensing or conveying under this
|
394 |
+
License, you may add to a covered work material governed by the terms
|
395 |
+
of that license document, provided that the further restriction does
|
396 |
+
not survive such relicensing or conveying.
|
397 |
+
|
398 |
+
If you add terms to a covered work in accord with this section, you
|
399 |
+
must place, in the relevant source files, a statement of the
|
400 |
+
additional terms that apply to those files, or a notice indicating
|
401 |
+
where to find the applicable terms.
|
402 |
+
|
403 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
404 |
+
form of a separately written license, or stated as exceptions;
|
405 |
+
the above requirements apply either way.
|
406 |
+
|
407 |
+
8. Termination.
|
408 |
+
|
409 |
+
You may not propagate or modify a covered work except as expressly
|
410 |
+
provided under this License. Any attempt otherwise to propagate or
|
411 |
+
modify it is void, and will automatically terminate your rights under
|
412 |
+
this License (including any patent licenses granted under the third
|
413 |
+
paragraph of section 11).
|
414 |
+
|
415 |
+
However, if you cease all violation of this License, then your
|
416 |
+
license from a particular copyright holder is reinstated (a)
|
417 |
+
provisionally, unless and until the copyright holder explicitly and
|
418 |
+
finally terminates your license, and (b) permanently, if the copyright
|
419 |
+
holder fails to notify you of the violation by some reasonable means
|
420 |
+
prior to 60 days after the cessation.
|
421 |
+
|
422 |
+
Moreover, your license from a particular copyright holder is
|
423 |
+
reinstated permanently if the copyright holder notifies you of the
|
424 |
+
violation by some reasonable means, this is the first time you have
|
425 |
+
received notice of violation of this License (for any work) from that
|
426 |
+
copyright holder, and you cure the violation prior to 30 days after
|
427 |
+
your receipt of the notice.
|
428 |
+
|
429 |
+
Termination of your rights under this section does not terminate the
|
430 |
+
licenses of parties who have received copies or rights from you under
|
431 |
+
this License. If your rights have been terminated and not permanently
|
432 |
+
reinstated, you do not qualify to receive new licenses for the same
|
433 |
+
material under section 10.
|
434 |
+
|
435 |
+
9. Acceptance Not Required for Having Copies.
|
436 |
+
|
437 |
+
You are not required to accept this License in order to receive or
|
438 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
439 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
440 |
+
to receive a copy likewise does not require acceptance. However,
|
441 |
+
nothing other than this License grants you permission to propagate or
|
442 |
+
modify any covered work. These actions infringe copyright if you do
|
443 |
+
not accept this License. Therefore, by modifying or propagating a
|
444 |
+
covered work, you indicate your acceptance of this License to do so.
|
445 |
+
|
446 |
+
10. Automatic Licensing of Downstream Recipients.
|
447 |
+
|
448 |
+
Each time you convey a covered work, the recipient automatically
|
449 |
+
receives a license from the original licensors, to run, modify and
|
450 |
+
propagate that work, subject to this License. You are not responsible
|
451 |
+
for enforcing compliance by third parties with this License.
|
452 |
+
|
453 |
+
An "entity transaction" is a transaction transferring control of an
|
454 |
+
organization, or substantially all assets of one, or subdividing an
|
455 |
+
organization, or merging organizations. If propagation of a covered
|
456 |
+
work results from an entity transaction, each party to that
|
457 |
+
transaction who receives a copy of the work also receives whatever
|
458 |
+
licenses to the work the party's predecessor in interest had or could
|
459 |
+
give under the previous paragraph, plus a right to possession of the
|
460 |
+
Corresponding Source of the work from the predecessor in interest, if
|
461 |
+
the predecessor has it or can get it with reasonable efforts.
|
462 |
+
|
463 |
+
You may not impose any further restrictions on the exercise of the
|
464 |
+
rights granted or affirmed under this License. For example, you may
|
465 |
+
not impose a license fee, royalty, or other charge for exercise of
|
466 |
+
rights granted under this License, and you may not initiate litigation
|
467 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
468 |
+
any patent claim is infringed by making, using, selling, offering for
|
469 |
+
sale, or importing the Program or any portion of it.
|
470 |
+
|
471 |
+
11. Patents.
|
472 |
+
|
473 |
+
A "contributor" is a copyright holder who authorizes use under this
|
474 |
+
License of the Program or a work on which the Program is based. The
|
475 |
+
work thus licensed is called the contributor's "contributor version".
|
476 |
+
|
477 |
+
A contributor's "essential patent claims" are all patent claims
|
478 |
+
owned or controlled by the contributor, whether already acquired or
|
479 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
480 |
+
by this License, of making, using, or selling its contributor version,
|
481 |
+
but do not include claims that would be infringed only as a
|
482 |
+
consequence of further modification of the contributor version. For
|
483 |
+
purposes of this definition, "control" includes the right to grant
|
484 |
+
patent sublicenses in a manner consistent with the requirements of
|
485 |
+
this License.
|
486 |
+
|
487 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
488 |
+
patent license under the contributor's essential patent claims, to
|
489 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
490 |
+
propagate the contents of its contributor version.
|
491 |
+
|
492 |
+
In the following three paragraphs, a "patent license" is any express
|
493 |
+
agreement or commitment, however denominated, not to enforce a patent
|
494 |
+
(such as an express permission to practice a patent or covenant not to
|
495 |
+
sue for patent infringement). To "grant" such a patent license to a
|
496 |
+
party means to make such an agreement or commitment not to enforce a
|
497 |
+
patent against the party.
|
498 |
+
|
499 |
+
If you convey a covered work, knowingly relying on a patent license,
|
500 |
+
and the Corresponding Source of the work is not available for anyone
|
501 |
+
to copy, free of charge and under the terms of this License, through a
|
502 |
+
publicly available network server or other readily accessible means,
|
503 |
+
then you must either (1) cause the Corresponding Source to be so
|
504 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
505 |
+
patent license for this particular work, or (3) arrange, in a manner
|
506 |
+
consistent with the requirements of this License, to extend the patent
|
507 |
+
license to downstream recipients. "Knowingly relying" means you have
|
508 |
+
actual knowledge that, but for the patent license, your conveying the
|
509 |
+
covered work in a country, or your recipient's use of the covered work
|
510 |
+
in a country, would infringe one or more identifiable patents in that
|
511 |
+
country that you have reason to believe are valid.
|
512 |
+
|
513 |
+
If, pursuant to or in connection with a single transaction or
|
514 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
515 |
+
covered work, and grant a patent license to some of the parties
|
516 |
+
receiving the covered work authorizing them to use, propagate, modify
|
517 |
+
or convey a specific copy of the covered work, then the patent license
|
518 |
+
you grant is automatically extended to all recipients of the covered
|
519 |
+
work and works based on it.
|
520 |
+
|
521 |
+
A patent license is "discriminatory" if it does not include within
|
522 |
+
the scope of its coverage, prohibits the exercise of, or is
|
523 |
+
conditioned on the non-exercise of one or more of the rights that are
|
524 |
+
specifically granted under this License. You may not convey a covered
|
525 |
+
work if you are a party to an arrangement with a third party that is
|
526 |
+
in the business of distributing software, under which you make payment
|
527 |
+
to the third party based on the extent of your activity of conveying
|
528 |
+
the work, and under which the third party grants, to any of the
|
529 |
+
parties who would receive the covered work from you, a discriminatory
|
530 |
+
patent license (a) in connection with copies of the covered work
|
531 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
532 |
+
for and in connection with specific products or compilations that
|
533 |
+
contain the covered work, unless you entered into that arrangement,
|
534 |
+
or that patent license was granted, prior to 28 March 2007.
|
535 |
+
|
536 |
+
Nothing in this License shall be construed as excluding or limiting
|
537 |
+
any implied license or other defenses to infringement that may
|
538 |
+
otherwise be available to you under applicable patent law.
|
539 |
+
|
540 |
+
12. No Surrender of Others' Freedom.
|
541 |
+
|
542 |
+
If conditions are imposed on you (whether by court order, agreement or
|
543 |
+
otherwise) that contradict the conditions of this License, they do not
|
544 |
+
excuse you from the conditions of this License. If you cannot convey a
|
545 |
+
covered work so as to satisfy simultaneously your obligations under this
|
546 |
+
License and any other pertinent obligations, then as a consequence you may
|
547 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
548 |
+
to collect a royalty for further conveying from those to whom you convey
|
549 |
+
the Program, the only way you could satisfy both those terms and this
|
550 |
+
License would be to refrain entirely from conveying the Program.
|
551 |
+
|
552 |
+
13. Use with the GNU Affero General Public License.
|
553 |
+
|
554 |
+
Notwithstanding any other provision of this License, you have
|
555 |
+
permission to link or combine any covered work with a work licensed
|
556 |
+
under version 3 of the GNU Affero General Public License into a single
|
557 |
+
combined work, and to convey the resulting work. The terms of this
|
558 |
+
License will continue to apply to the part which is the covered work,
|
559 |
+
but the special requirements of the GNU Affero General Public License,
|
560 |
+
section 13, concerning interaction through a network will apply to the
|
561 |
+
combination as such.
|
562 |
+
|
563 |
+
14. Revised Versions of this License.
|
564 |
+
|
565 |
+
The Free Software Foundation may publish revised and/or new versions of
|
566 |
+
the GNU General Public License from time to time. Such new versions will
|
567 |
+
be similar in spirit to the present version, but may differ in detail to
|
568 |
+
address new problems or concerns.
|
569 |
+
|
570 |
+
Each version is given a distinguishing version number. If the
|
571 |
+
Program specifies that a certain numbered version of the GNU General
|
572 |
+
Public License "or any later version" applies to it, you have the
|
573 |
+
option of following the terms and conditions either of that numbered
|
574 |
+
version or of any later version published by the Free Software
|
575 |
+
Foundation. If the Program does not specify a version number of the
|
576 |
+
GNU General Public License, you may choose any version ever published
|
577 |
+
by the Free Software Foundation.
|
578 |
+
|
579 |
+
If the Program specifies that a proxy can decide which future
|
580 |
+
versions of the GNU General Public License can be used, that proxy's
|
581 |
+
public statement of acceptance of a version permanently authorizes you
|
582 |
+
to choose that version for the Program.
|
583 |
+
|
584 |
+
Later license versions may give you additional or different
|
585 |
+
permissions. However, no additional obligations are imposed on any
|
586 |
+
author or copyright holder as a result of your choosing to follow a
|
587 |
+
later version.
|
588 |
+
|
589 |
+
15. Disclaimer of Warranty.
|
590 |
+
|
591 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
592 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
593 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
594 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
595 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
596 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
597 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
598 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
599 |
+
|
600 |
+
16. Limitation of Liability.
|
601 |
+
|
602 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
603 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
604 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
605 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
606 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
607 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
608 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
609 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
610 |
+
SUCH DAMAGES.
|
611 |
+
|
612 |
+
17. Interpretation of Sections 15 and 16.
|
613 |
+
|
614 |
+
If the disclaimer of warranty and limitation of liability provided
|
615 |
+
above cannot be given local legal effect according to their terms,
|
616 |
+
reviewing courts shall apply local law that most closely approximates
|
617 |
+
an absolute waiver of all civil liability in connection with the
|
618 |
+
Program, unless a warranty or assumption of liability accompanies a
|
619 |
+
copy of the Program in return for a fee.
|
620 |
+
|
621 |
+
END OF TERMS AND CONDITIONS
|
622 |
+
|
623 |
+
How to Apply These Terms to Your New Programs
|
624 |
+
|
625 |
+
If you develop a new program, and you want it to be of the greatest
|
626 |
+
possible use to the public, the best way to achieve this is to make it
|
627 |
+
free software which everyone can redistribute and change under these terms.
|
628 |
+
|
629 |
+
To do so, attach the following notices to the program. It is safest
|
630 |
+
to attach them to the start of each source file to most effectively
|
631 |
+
state the exclusion of warranty; and each file should have at least
|
632 |
+
the "copyright" line and a pointer to where the full notice is found.
|
633 |
+
|
634 |
+
<one line to give the program's name and a brief idea of what it does.>
|
635 |
+
Copyright (C) <year> <name of author>
|
636 |
+
|
637 |
+
This program is free software: you can redistribute it and/or modify
|
638 |
+
it under the terms of the GNU General Public License as published by
|
639 |
+
the Free Software Foundation, either version 3 of the License, or
|
640 |
+
(at your option) any later version.
|
641 |
+
|
642 |
+
This program is distributed in the hope that it will be useful,
|
643 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
644 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
645 |
+
GNU General Public License for more details.
|
646 |
+
|
647 |
+
You should have received a copy of the GNU General Public License
|
648 |
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
649 |
+
|
650 |
+
Also add information on how to contact you by electronic and paper mail.
|
651 |
+
|
652 |
+
If the program does terminal interaction, make it output a short
|
653 |
+
notice like this when it starts in an interactive mode:
|
654 |
+
|
655 |
+
<program> Copyright (C) <year> <name of author>
|
656 |
+
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
657 |
+
This is free software, and you are welcome to redistribute it
|
658 |
+
under certain conditions; type `show c' for details.
|
659 |
+
|
660 |
+
The hypothetical commands `show w' and `show c' should show the appropriate
|
661 |
+
parts of the General Public License. Of course, your program's commands
|
662 |
+
might be different; for a GUI interface, you would use an "about box".
|
663 |
+
|
664 |
+
You should also get your employer (if you work as a programmer) or school,
|
665 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
666 |
+
For more information on this, and how to apply and follow the GNU GPL, see
|
667 |
+
<https://www.gnu.org/licenses/>.
|
668 |
+
|
669 |
+
The GNU General Public License does not permit incorporating your program
|
670 |
+
into proprietary programs. If your program is a subroutine library, you
|
671 |
+
may consider it more useful to permit linking proprietary applications with
|
672 |
+
the library. If this is what you want to do, use the GNU Lesser General
|
673 |
+
Public License instead of this License. But first, please read
|
674 |
+
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
README.md
ADDED
@@ -0,0 +1,238 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
ComfyUI
|
2 |
+
=======
|
3 |
+
The most powerful and modular stable diffusion GUI and backend.
|
4 |
+
-----------
|
5 |
+

|
6 |
+
|
7 |
+
This ui will let you design and execute advanced stable diffusion pipelines using a graph/nodes/flowchart based interface. For some workflow examples and see what ComfyUI can do you can check out:
|
8 |
+
### [ComfyUI Examples](https://comfyanonymous.github.io/ComfyUI_examples/)
|
9 |
+
|
10 |
+
### [Installing ComfyUI](#installing)
|
11 |
+
|
12 |
+
## Features
|
13 |
+
- Nodes/graph/flowchart interface to experiment and create complex Stable Diffusion workflows without needing to code anything.
|
14 |
+
- Fully supports SD1.x, SD2.x, [SDXL](https://comfyanonymous.github.io/ComfyUI_examples/sdxl/), [Stable Video Diffusion](https://comfyanonymous.github.io/ComfyUI_examples/video/), [Stable Cascade](https://comfyanonymous.github.io/ComfyUI_examples/stable_cascade/), [SD3](https://comfyanonymous.github.io/ComfyUI_examples/sd3/) and [Stable Audio](https://comfyanonymous.github.io/ComfyUI_examples/audio/)
|
15 |
+
- [Flux](https://comfyanonymous.github.io/ComfyUI_examples/flux/)
|
16 |
+
- Asynchronous Queue system
|
17 |
+
- Many optimizations: Only re-executes the parts of the workflow that changes between executions.
|
18 |
+
- Smart memory management: can automatically run models on GPUs with as low as 1GB vram.
|
19 |
+
- Works even if you don't have a GPU with: ```--cpu``` (slow)
|
20 |
+
- Can load ckpt, safetensors and diffusers models/checkpoints. Standalone VAEs and CLIP models.
|
21 |
+
- Embeddings/Textual inversion
|
22 |
+
- [Loras (regular, locon and loha)](https://comfyanonymous.github.io/ComfyUI_examples/lora/)
|
23 |
+
- [Hypernetworks](https://comfyanonymous.github.io/ComfyUI_examples/hypernetworks/)
|
24 |
+
- Loading full workflows (with seeds) from generated PNG, WebP and FLAC files.
|
25 |
+
- Saving/Loading workflows as Json files.
|
26 |
+
- Nodes interface can be used to create complex workflows like one for [Hires fix](https://comfyanonymous.github.io/ComfyUI_examples/2_pass_txt2img/) or much more advanced ones.
|
27 |
+
- [Area Composition](https://comfyanonymous.github.io/ComfyUI_examples/area_composition/)
|
28 |
+
- [Inpainting](https://comfyanonymous.github.io/ComfyUI_examples/inpaint/) with both regular and inpainting models.
|
29 |
+
- [ControlNet and T2I-Adapter](https://comfyanonymous.github.io/ComfyUI_examples/controlnet/)
|
30 |
+
- [Upscale Models (ESRGAN, ESRGAN variants, SwinIR, Swin2SR, etc...)](https://comfyanonymous.github.io/ComfyUI_examples/upscale_models/)
|
31 |
+
- [unCLIP Models](https://comfyanonymous.github.io/ComfyUI_examples/unclip/)
|
32 |
+
- [GLIGEN](https://comfyanonymous.github.io/ComfyUI_examples/gligen/)
|
33 |
+
- [Model Merging](https://comfyanonymous.github.io/ComfyUI_examples/model_merging/)
|
34 |
+
- [LCM models and Loras](https://comfyanonymous.github.io/ComfyUI_examples/lcm/)
|
35 |
+
- [SDXL Turbo](https://comfyanonymous.github.io/ComfyUI_examples/sdturbo/)
|
36 |
+
- [AuraFlow](https://comfyanonymous.github.io/ComfyUI_examples/aura_flow/)
|
37 |
+
- [HunyuanDiT](https://comfyanonymous.github.io/ComfyUI_examples/hunyuan_dit/)
|
38 |
+
- Latent previews with [TAESD](#how-to-show-high-quality-previews)
|
39 |
+
- Starts up very fast.
|
40 |
+
- Works fully offline: will never download anything.
|
41 |
+
- [Config file](extra_model_paths.yaml.example) to set the search paths for models.
|
42 |
+
|
43 |
+
Workflow examples can be found on the [Examples page](https://comfyanonymous.github.io/ComfyUI_examples/)
|
44 |
+
|
45 |
+
## Shortcuts
|
46 |
+
|
47 |
+
| Keybind | Explanation |
|
48 |
+
|------------------------------------|--------------------------------------------------------------------------------------------------------------------|
|
49 |
+
| Ctrl + Enter | Queue up current graph for generation |
|
50 |
+
| Ctrl + Shift + Enter | Queue up current graph as first for generation |
|
51 |
+
| Ctrl + Z/Ctrl + Y | Undo/Redo |
|
52 |
+
| Ctrl + S | Save workflow |
|
53 |
+
| Ctrl + O | Load workflow |
|
54 |
+
| Ctrl + A | Select all nodes |
|
55 |
+
| Alt + C | Collapse/uncollapse selected nodes |
|
56 |
+
| Ctrl + M | Mute/unmute selected nodes |
|
57 |
+
| Ctrl + B | Bypass selected nodes (acts like the node was removed from the graph and the wires reconnected through) |
|
58 |
+
| Delete/Backspace | Delete selected nodes |
|
59 |
+
| Ctrl + Backspace | Delete the current graph |
|
60 |
+
| Space | Move the canvas around when held and moving the cursor |
|
61 |
+
| Ctrl/Shift + Click | Add clicked node to selection |
|
62 |
+
| Ctrl + C/Ctrl + V | Copy and paste selected nodes (without maintaining connections to outputs of unselected nodes) |
|
63 |
+
| Ctrl + C/Ctrl + Shift + V | Copy and paste selected nodes (maintaining connections from outputs of unselected nodes to inputs of pasted nodes) |
|
64 |
+
| Shift + Drag | Move multiple selected nodes at the same time |
|
65 |
+
| Ctrl + D | Load default graph |
|
66 |
+
| Alt + `+` | Canvas Zoom in |
|
67 |
+
| Alt + `-` | Canvas Zoom out |
|
68 |
+
| Ctrl + Shift + LMB + Vertical drag | Canvas Zoom in/out |
|
69 |
+
| Q | Toggle visibility of the queue |
|
70 |
+
| H | Toggle visibility of history |
|
71 |
+
| R | Refresh graph |
|
72 |
+
| Double-Click LMB | Open node quick search palette |
|
73 |
+
|
74 |
+
Ctrl can also be replaced with Cmd instead for macOS users
|
75 |
+
|
76 |
+
# Installing
|
77 |
+
|
78 |
+
## Windows
|
79 |
+
|
80 |
+
There is a portable standalone build for Windows that should work for running on Nvidia GPUs or for running on your CPU only on the [releases page](https://github.com/comfyanonymous/ComfyUI/releases).
|
81 |
+
|
82 |
+
### [Direct link to download](https://github.com/comfyanonymous/ComfyUI/releases/latest/download/ComfyUI_windows_portable_nvidia.7z)
|
83 |
+
|
84 |
+
Simply download, extract with [7-Zip](https://7-zip.org) and run. Make sure you put your Stable Diffusion checkpoints/models (the huge ckpt/safetensors files) in: ComfyUI\models\checkpoints
|
85 |
+
|
86 |
+
If you have trouble extracting it, right click the file -> properties -> unblock
|
87 |
+
|
88 |
+
#### How do I share models between another UI and ComfyUI?
|
89 |
+
|
90 |
+
See the [Config file](extra_model_paths.yaml.example) to set the search paths for models. In the standalone windows build you can find this file in the ComfyUI directory. Rename this file to extra_model_paths.yaml and edit it with your favorite text editor.
|
91 |
+
|
92 |
+
## Jupyter Notebook
|
93 |
+
|
94 |
+
To run it on services like paperspace, kaggle or colab you can use my [Jupyter Notebook](notebooks/comfyui_colab.ipynb)
|
95 |
+
|
96 |
+
## Manual Install (Windows, Linux)
|
97 |
+
|
98 |
+
Git clone this repo.
|
99 |
+
|
100 |
+
Put your SD checkpoints (the huge ckpt/safetensors files) in: models/checkpoints
|
101 |
+
|
102 |
+
Put your VAE in: models/vae
|
103 |
+
|
104 |
+
|
105 |
+
### AMD GPUs (Linux only)
|
106 |
+
AMD users can install rocm and pytorch with pip if you don't have it already installed, this is the command to install the stable version:
|
107 |
+
|
108 |
+
```pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/rocm6.0```
|
109 |
+
|
110 |
+
This is the command to install the nightly with ROCm 6.0 which might have some performance improvements:
|
111 |
+
|
112 |
+
```pip install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/rocm6.1```
|
113 |
+
|
114 |
+
### NVIDIA
|
115 |
+
|
116 |
+
Nvidia users should install stable pytorch using this command:
|
117 |
+
|
118 |
+
```pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu121```
|
119 |
+
|
120 |
+
This is the command to install pytorch nightly instead which might have performance improvements:
|
121 |
+
|
122 |
+
```pip install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/cu124```
|
123 |
+
|
124 |
+
#### Troubleshooting
|
125 |
+
|
126 |
+
If you get the "Torch not compiled with CUDA enabled" error, uninstall torch with:
|
127 |
+
|
128 |
+
```pip uninstall torch```
|
129 |
+
|
130 |
+
And install it again with the command above.
|
131 |
+
|
132 |
+
### Dependencies
|
133 |
+
|
134 |
+
Install the dependencies by opening your terminal inside the ComfyUI folder and:
|
135 |
+
|
136 |
+
```pip install -r requirements.txt```
|
137 |
+
|
138 |
+
After this you should have everything installed and can proceed to running ComfyUI.
|
139 |
+
|
140 |
+
### Others:
|
141 |
+
|
142 |
+
#### Intel GPUs
|
143 |
+
|
144 |
+
Intel GPU support is available for all Intel GPUs supported by Intel's Extension for Pytorch (IPEX) with the support requirements listed in the [Installation](https://intel.github.io/intel-extension-for-pytorch/index.html#installation?platform=gpu) page. Choose your platform and method of install and follow the instructions. The steps are as follows:
|
145 |
+
|
146 |
+
1. Start by installing the drivers or kernel listed or newer in the Installation page of IPEX linked above for Windows and Linux if needed.
|
147 |
+
1. Follow the instructions to install [Intel's oneAPI Basekit](https://www.intel.com/content/www/us/en/developer/tools/oneapi/base-toolkit-download.html) for your platform.
|
148 |
+
1. Install the packages for IPEX using the instructions provided in the Installation page for your platform.
|
149 |
+
1. Follow the [ComfyUI manual installation](#manual-install-windows-linux) instructions for Windows and Linux and run ComfyUI normally as described above after everything is installed.
|
150 |
+
|
151 |
+
Additional discussion and help can be found [here](https://github.com/comfyanonymous/ComfyUI/discussions/476).
|
152 |
+
|
153 |
+
#### Apple Mac silicon
|
154 |
+
|
155 |
+
You can install ComfyUI in Apple Mac silicon (M1 or M2) with any recent macOS version.
|
156 |
+
|
157 |
+
1. Install pytorch nightly. For instructions, read the [Accelerated PyTorch training on Mac](https://developer.apple.com/metal/pytorch/) Apple Developer guide (make sure to install the latest pytorch nightly).
|
158 |
+
1. Follow the [ComfyUI manual installation](#manual-install-windows-linux) instructions for Windows and Linux.
|
159 |
+
1. Install the ComfyUI [dependencies](#dependencies). If you have another Stable Diffusion UI [you might be able to reuse the dependencies](#i-already-have-another-ui-for-stable-diffusion-installed-do-i-really-have-to-install-all-of-these-dependencies).
|
160 |
+
1. Launch ComfyUI by running `python main.py`
|
161 |
+
|
162 |
+
> **Note**: Remember to add your models, VAE, LoRAs etc. to the corresponding Comfy folders, as discussed in [ComfyUI manual installation](#manual-install-windows-linux).
|
163 |
+
|
164 |
+
#### DirectML (AMD Cards on Windows)
|
165 |
+
|
166 |
+
```pip install torch-directml``` Then you can launch ComfyUI with: ```python main.py --directml```
|
167 |
+
|
168 |
+
### I already have another UI for Stable Diffusion installed do I really have to install all of these dependencies?
|
169 |
+
|
170 |
+
You don't. If you have another UI installed and working with its own python venv you can use that venv to run ComfyUI. You can open up your favorite terminal and activate it:
|
171 |
+
|
172 |
+
```source path_to_other_sd_gui/venv/bin/activate```
|
173 |
+
|
174 |
+
or on Windows:
|
175 |
+
|
176 |
+
With Powershell: ```"path_to_other_sd_gui\venv\Scripts\Activate.ps1"```
|
177 |
+
|
178 |
+
With cmd.exe: ```"path_to_other_sd_gui\venv\Scripts\activate.bat"```
|
179 |
+
|
180 |
+
And then you can use that terminal to run ComfyUI without installing any dependencies. Note that the venv folder might be called something else depending on the SD UI.
|
181 |
+
|
182 |
+
# Running
|
183 |
+
|
184 |
+
```python main.py```
|
185 |
+
|
186 |
+
### For AMD cards not officially supported by ROCm
|
187 |
+
|
188 |
+
Try running it with this command if you have issues:
|
189 |
+
|
190 |
+
For 6700, 6600 and maybe other RDNA2 or older: ```HSA_OVERRIDE_GFX_VERSION=10.3.0 python main.py```
|
191 |
+
|
192 |
+
For AMD 7600 and maybe other RDNA3 cards: ```HSA_OVERRIDE_GFX_VERSION=11.0.0 python main.py```
|
193 |
+
|
194 |
+
# Notes
|
195 |
+
|
196 |
+
Only parts of the graph that have an output with all the correct inputs will be executed.
|
197 |
+
|
198 |
+
Only parts of the graph that change from each execution to the next will be executed, if you submit the same graph twice only the first will be executed. If you change the last part of the graph only the part you changed and the part that depends on it will be executed.
|
199 |
+
|
200 |
+
Dragging a generated png on the webpage or loading one will give you the full workflow including seeds that were used to create it.
|
201 |
+
|
202 |
+
You can use () to change emphasis of a word or phrase like: (good code:1.2) or (bad code:0.8). The default emphasis for () is 1.1. To use () characters in your actual prompt escape them like \\( or \\).
|
203 |
+
|
204 |
+
You can use {day|night}, for wildcard/dynamic prompts. With this syntax "{wild|card|test}" will be randomly replaced by either "wild", "card" or "test" by the frontend every time you queue the prompt. To use {} characters in your actual prompt escape them like: \\{ or \\}.
|
205 |
+
|
206 |
+
Dynamic prompts also support C-style comments, like `// comment` or `/* comment */`.
|
207 |
+
|
208 |
+
To use a textual inversion concepts/embeddings in a text prompt put them in the models/embeddings directory and use them in the CLIPTextEncode node like this (you can omit the .pt extension):
|
209 |
+
|
210 |
+
```embedding:embedding_filename.pt```
|
211 |
+
|
212 |
+
|
213 |
+
## How to show high-quality previews?
|
214 |
+
|
215 |
+
Use ```--preview-method auto``` to enable previews.
|
216 |
+
|
217 |
+
The default installation includes a fast latent preview method that's low-resolution. To enable higher-quality previews with [TAESD](https://github.com/madebyollin/taesd), download the [taesd_decoder.pth](https://github.com/madebyollin/taesd/raw/main/taesd_decoder.pth) (for SD1.x and SD2.x) and [taesdxl_decoder.pth](https://github.com/madebyollin/taesd/raw/main/taesdxl_decoder.pth) (for SDXL) models and place them in the `models/vae_approx` folder. Once they're installed, restart ComfyUI to enable high-quality previews.
|
218 |
+
|
219 |
+
## How to use TLS/SSL?
|
220 |
+
Generate a self-signed certificate (not appropriate for shared/production use) and key by running the command: `openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -sha256 -days 3650 -nodes -subj "/C=XX/ST=StateName/L=CityName/O=CompanyName/OU=CompanySectionName/CN=CommonNameOrHostname"`
|
221 |
+
|
222 |
+
Use `--tls-keyfile key.pem --tls-certfile cert.pem` to enable TLS/SSL, the app will now be accessible with `https://...` instead of `http://...`.
|
223 |
+
|
224 |
+
> Note: Windows users can use [alexisrolland/docker-openssl](https://github.com/alexisrolland/docker-openssl) or one of the [3rd party binary distributions](https://wiki.openssl.org/index.php/Binaries) to run the command example above.
|
225 |
+
<br/><br/>If you use a container, note that the volume mount `-v` can be a relative path so `... -v ".\:/openssl-certs" ...` would create the key & cert files in the current directory of your command prompt or powershell terminal.
|
226 |
+
|
227 |
+
## Support and dev channel
|
228 |
+
|
229 |
+
[Matrix space: #comfyui_space:matrix.org](https://app.element.io/#/room/%23comfyui_space%3Amatrix.org) (it's like discord but open source).
|
230 |
+
|
231 |
+
See also: [https://www.comfy.org/](https://www.comfy.org/)
|
232 |
+
|
233 |
+
# QA
|
234 |
+
|
235 |
+
### Which GPU should I buy for this?
|
236 |
+
|
237 |
+
[See this page for some recommendations](https://github.com/comfyanonymous/ComfyUI/wiki/Which-GPU-should-I-buy-for-ComfyUI)
|
238 |
+
|
app.py
ADDED
@@ -0,0 +1,420 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import random
|
3 |
+
import sys
|
4 |
+
from typing import Sequence, Mapping, Any, Union
|
5 |
+
import torch
|
6 |
+
import gradio as gr
|
7 |
+
import subprocess
|
8 |
+
|
9 |
+
# List of GitHub repositories
|
10 |
+
custom_nodes = [
|
11 |
+
"https://github.com/ltdrdata/ComfyUI-Manager",
|
12 |
+
"https://github.com/BadCafeCode/masquerade-nodes-comfyui",
|
13 |
+
"https://github.com/pythongosssss/ComfyUI-Custom-Scripts",
|
14 |
+
"https://github.com/Suzie1/ComfyUI_Comfyroll_CustomNodes",
|
15 |
+
"https://github.com/rgthree/rgthree-comfy",
|
16 |
+
"https://github.com/cubiq/ComfyUI_essentials",
|
17 |
+
"https://github.com/chrisgoringe/cg-use-everywhere",
|
18 |
+
"https://github.com/kijai/ComfyUI-KJNodes",
|
19 |
+
"https://github.com/kijai/ComfyUI-Florence2",
|
20 |
+
"https://github.com/chflame163/ComfyUI_LayerStyle_Advance",
|
21 |
+
"https://github.com/Ryuukeisyou/comfyui_face_parsing"
|
22 |
+
]
|
23 |
+
|
24 |
+
# Set download directory
|
25 |
+
custom_nodes_dir = "models/custom_nodes"
|
26 |
+
|
27 |
+
# Ensure the directory exists
|
28 |
+
os.makedirs(custom_nodes_dir, exist_ok=True)
|
29 |
+
|
30 |
+
# Clone or update repositories
|
31 |
+
for repo in custom_nodes:
|
32 |
+
repo_name = repo.split("/")[-1] # Extract repo name
|
33 |
+
repo_path = os.path.join(custom_nodes_dir, repo_name)
|
34 |
+
|
35 |
+
if os.path.exists(repo_path):
|
36 |
+
print(f"Updating {repo_name}...")
|
37 |
+
subprocess.run(["git", "-C", repo_path, "pull"], check=True)
|
38 |
+
else:
|
39 |
+
print(f"Cloning {repo_name}...")
|
40 |
+
subprocess.run(["git", "clone", repo, repo_path], check=True)
|
41 |
+
|
42 |
+
print("✅ All custom nodes downloaded successfully!")
|
43 |
+
|
44 |
+
os.system('wget "https://civitai.com/api/download/models/646523?token=bf69329f11656d7676d81889385b4645" -O "models/checkpoints/epic_realsim_02.safetensors"')
|
45 |
+
|
46 |
+
|
47 |
+
|
48 |
+
def get_value_at_index(obj: Union[Sequence, Mapping], index: int) -> Any:
|
49 |
+
"""Returns the value at the given index of a sequence or mapping.
|
50 |
+
|
51 |
+
If the object is a sequence (like list or string), returns the value at the given index.
|
52 |
+
If the object is a mapping (like a dictionary), returns the value at the index-th key.
|
53 |
+
|
54 |
+
Some return a dictionary, in these cases, we look for the "results" key
|
55 |
+
|
56 |
+
Args:
|
57 |
+
obj (Union[Sequence, Mapping]): The object to retrieve the value from.
|
58 |
+
index (int): The index of the value to retrieve.
|
59 |
+
|
60 |
+
Returns:
|
61 |
+
Any: The value at the given index.
|
62 |
+
|
63 |
+
Raises:
|
64 |
+
IndexError: If the index is out of bounds for the object and the object is not a mapping.
|
65 |
+
"""
|
66 |
+
try:
|
67 |
+
return obj[index]
|
68 |
+
except KeyError:
|
69 |
+
return obj["result"][index]
|
70 |
+
|
71 |
+
|
72 |
+
def find_path(name: str, path: str = None) -> str:
|
73 |
+
"""
|
74 |
+
Recursively looks at parent folders starting from the given path until it finds the given name.
|
75 |
+
Returns the path as a Path object if found, or None otherwise.
|
76 |
+
"""
|
77 |
+
# If no path is given, use the current working directory
|
78 |
+
if path is None:
|
79 |
+
path = os.getcwd()
|
80 |
+
|
81 |
+
# Check if the current directory contains the name
|
82 |
+
if name in os.listdir(path):
|
83 |
+
path_name = os.path.join(path, name)
|
84 |
+
print(f"{name} found: {path_name}")
|
85 |
+
return path_name
|
86 |
+
|
87 |
+
# Get the parent directory
|
88 |
+
parent_directory = os.path.dirname(path)
|
89 |
+
|
90 |
+
# If the parent directory is the same as the current directory, we've reached the root and stop the search
|
91 |
+
if parent_directory == path:
|
92 |
+
return None
|
93 |
+
|
94 |
+
# Recursively call the function with the parent directory
|
95 |
+
return find_path(name, parent_directory)
|
96 |
+
|
97 |
+
|
98 |
+
def add_comfyui_directory_to_sys_path() -> None:
|
99 |
+
"""
|
100 |
+
Add 'ComfyUI' to the sys.path
|
101 |
+
"""
|
102 |
+
comfyui_path = find_path("ComfyUI")
|
103 |
+
if comfyui_path is not None and os.path.isdir(comfyui_path):
|
104 |
+
sys.path.append(comfyui_path)
|
105 |
+
print(f"'{comfyui_path}' added to sys.path")
|
106 |
+
|
107 |
+
|
108 |
+
def add_extra_model_paths() -> None:
|
109 |
+
"""
|
110 |
+
Parse the optional extra_model_paths.yaml file and add the parsed paths to the sys.path.
|
111 |
+
"""
|
112 |
+
try:
|
113 |
+
from main import load_extra_path_config
|
114 |
+
except ImportError:
|
115 |
+
print(
|
116 |
+
"Could not import load_extra_path_config from main.py. Looking in utils.extra_config instead."
|
117 |
+
)
|
118 |
+
from utils.extra_config import load_extra_path_config
|
119 |
+
|
120 |
+
extra_model_paths = find_path("extra_model_paths.yaml")
|
121 |
+
|
122 |
+
if extra_model_paths is not None:
|
123 |
+
load_extra_path_config(extra_model_paths)
|
124 |
+
else:
|
125 |
+
print("Could not find the extra_model_paths config file.")
|
126 |
+
|
127 |
+
|
128 |
+
add_comfyui_directory_to_sys_path()
|
129 |
+
add_extra_model_paths()
|
130 |
+
|
131 |
+
|
132 |
+
def import_custom_nodes() -> None:
|
133 |
+
"""Find all custom nodes in the custom_nodes folder and add those node objects to NODE_CLASS_MAPPINGS
|
134 |
+
|
135 |
+
This function sets up a new asyncio event loop, initializes the PromptServer,
|
136 |
+
creates a PromptQueue, and initializes the custom nodes.
|
137 |
+
"""
|
138 |
+
import asyncio
|
139 |
+
import execution
|
140 |
+
from nodes import init_extra_nodes
|
141 |
+
import server
|
142 |
+
|
143 |
+
# Creating a new event loop and setting it as the default loop
|
144 |
+
loop = asyncio.new_event_loop()
|
145 |
+
asyncio.set_event_loop(loop)
|
146 |
+
|
147 |
+
# Creating an instance of PromptServer with the loop
|
148 |
+
server_instance = server.PromptServer(loop)
|
149 |
+
execution.PromptQueue(server_instance)
|
150 |
+
|
151 |
+
# Initializing custom nodes
|
152 |
+
init_extra_nodes()
|
153 |
+
|
154 |
+
|
155 |
+
from nodes import NODE_CLASS_MAPPINGS
|
156 |
+
|
157 |
+
def generate_image(skin_image):
|
158 |
+
import_custom_nodes()
|
159 |
+
with torch.inference_mode():
|
160 |
+
checkpointloadersimple = NODE_CLASS_MAPPINGS["CheckpointLoaderSimple"]()
|
161 |
+
checkpointloadersimple_31 = checkpointloadersimple.load_checkpoint(
|
162 |
+
ckpt_name="epic_realsim_02.safetensors"
|
163 |
+
)
|
164 |
+
|
165 |
+
loraloader = NODE_CLASS_MAPPINGS["LoraLoader"]()
|
166 |
+
loraloader_133 = loraloader.load_lora(
|
167 |
+
lora_name="real-humans-prompts.safetensors",
|
168 |
+
strength_model=1,
|
169 |
+
strength_clip=1,
|
170 |
+
model=get_value_at_index(checkpointloadersimple_31, 0),
|
171 |
+
clip=get_value_at_index(checkpointloadersimple_31, 1),
|
172 |
+
)
|
173 |
+
|
174 |
+
cliptextencode = NODE_CLASS_MAPPINGS["CLIPTextEncode"]()
|
175 |
+
cliptextencode_35 = cliptextencode.encode(
|
176 |
+
text="Blurred, out of focus, low resolution, pixelated, cartoonish, unrealistic, overexposed, underexposed, flat lighting, distorted, artifacts, noise, extra limbs, deformed features, plastic skin, airbrushed, CGI, over-saturated colors, watermarks, text.",
|
177 |
+
clip=get_value_at_index(loraloader_133, 1),
|
178 |
+
)
|
179 |
+
|
180 |
+
loadimage = NODE_CLASS_MAPPINGS["LoadImage"]()
|
181 |
+
loadimage_120 = loadimage.load_image(image=skin_image)
|
182 |
+
|
183 |
+
vaeencode = NODE_CLASS_MAPPINGS["VAEEncode"]()
|
184 |
+
vaeencode_37 = vaeencode.encode(
|
185 |
+
vae=get_value_at_index(checkpointloadersimple_31, 2),
|
186 |
+
pixels=get_value_at_index(loadimage_120, 0),
|
187 |
+
)
|
188 |
+
|
189 |
+
faceparsingmodelloaderfaceparsing = NODE_CLASS_MAPPINGS[
|
190 |
+
"FaceParsingModelLoader(FaceParsing)"
|
191 |
+
]()
|
192 |
+
faceparsingmodelloaderfaceparsing_59 = faceparsingmodelloaderfaceparsing.main(
|
193 |
+
device="cuda"
|
194 |
+
)
|
195 |
+
|
196 |
+
faceparsingprocessorloaderfaceparsing = NODE_CLASS_MAPPINGS[
|
197 |
+
"FaceParsingProcessorLoader(FaceParsing)"
|
198 |
+
]()
|
199 |
+
faceparsingprocessorloaderfaceparsing_60 = (
|
200 |
+
faceparsingprocessorloaderfaceparsing.main()
|
201 |
+
)
|
202 |
+
|
203 |
+
downloadandloadflorence2model = NODE_CLASS_MAPPINGS[
|
204 |
+
"DownloadAndLoadFlorence2Model"
|
205 |
+
]()
|
206 |
+
downloadandloadflorence2model_126 = downloadandloadflorence2model.loadmodel(
|
207 |
+
model="microsoft/Florence-2-base", precision="fp16", attention="sdpa"
|
208 |
+
)
|
209 |
+
|
210 |
+
florence2run = NODE_CLASS_MAPPINGS["Florence2Run"]()
|
211 |
+
florence2run_125 = florence2run.encode(
|
212 |
+
text_input="",
|
213 |
+
task="more_detailed_caption",
|
214 |
+
fill_mask=False,
|
215 |
+
keep_model_loaded=False,
|
216 |
+
max_new_tokens=1024,
|
217 |
+
num_beams=3,
|
218 |
+
do_sample=True,
|
219 |
+
output_mask_select="",
|
220 |
+
seed=random.randint(1, 2**64),
|
221 |
+
image=get_value_at_index(loadimage_120, 0),
|
222 |
+
florence2_model=get_value_at_index(downloadandloadflorence2model_126, 0),
|
223 |
+
)
|
224 |
+
|
225 |
+
showtextpysssss = NODE_CLASS_MAPPINGS["ShowText|pysssss"]()
|
226 |
+
showtextpysssss_123 = showtextpysssss.notify(
|
227 |
+
text=get_value_at_index(florence2run_125, 2), unique_id=7970233141736593248
|
228 |
+
)
|
229 |
+
|
230 |
+
cr_combine_prompt = NODE_CLASS_MAPPINGS["CR Combine Prompt"]()
|
231 |
+
cr_combine_prompt_124 = cr_combine_prompt.get_value(
|
232 |
+
part1="closeup photo of a",
|
233 |
+
part2=get_value_at_index(showtextpysssss_123, 0),
|
234 |
+
part3="and realistic skin tones, imperfections and visible pores, photorealistic, soft diffused lighting, subsurface scattering, hyper-detailed shading, dynamic shadows, 8K resolution, cinematic lighting, masterpiece, intricate details, shot on a DSLR with a 50mm lens.",
|
235 |
+
part4="",
|
236 |
+
separator=" ",
|
237 |
+
)
|
238 |
+
|
239 |
+
cliptextencode_113 = cliptextencode.encode(
|
240 |
+
text=get_value_at_index(cr_combine_prompt_124, 0),
|
241 |
+
clip=get_value_at_index(loraloader_133, 1),
|
242 |
+
)
|
243 |
+
|
244 |
+
layermask_personmaskultra_v2 = NODE_CLASS_MAPPINGS[
|
245 |
+
"LayerMask: PersonMaskUltra V2"
|
246 |
+
]()
|
247 |
+
setlatentnoisemask = NODE_CLASS_MAPPINGS["SetLatentNoiseMask"]()
|
248 |
+
ksampler = NODE_CLASS_MAPPINGS["KSampler"]()
|
249 |
+
vaedecode = NODE_CLASS_MAPPINGS["VAEDecode"]()
|
250 |
+
maskpreview = NODE_CLASS_MAPPINGS["MaskPreview+"]()
|
251 |
+
faceparsefaceparsing = NODE_CLASS_MAPPINGS["FaceParse(FaceParsing)"]()
|
252 |
+
faceparsingresultsparserfaceparsing = NODE_CLASS_MAPPINGS[
|
253 |
+
"FaceParsingResultsParser(FaceParsing)"
|
254 |
+
]()
|
255 |
+
growmaskwithblur = NODE_CLASS_MAPPINGS["GrowMaskWithBlur"]()
|
256 |
+
masktoimage = NODE_CLASS_MAPPINGS["MaskToImage"]()
|
257 |
+
cut_by_mask = NODE_CLASS_MAPPINGS["Cut By Mask"]()
|
258 |
+
imagecompositemasked = NODE_CLASS_MAPPINGS["ImageCompositeMasked"]()
|
259 |
+
saveimage = NODE_CLASS_MAPPINGS["SaveImage"]()
|
260 |
+
anything_everywhere = NODE_CLASS_MAPPINGS["Anything Everywhere"]()
|
261 |
+
|
262 |
+
for q in range(1):
|
263 |
+
layermask_personmaskultra_v2_28 = (
|
264 |
+
layermask_personmaskultra_v2.person_mask_ultra_v2(
|
265 |
+
face=True,
|
266 |
+
hair=True,
|
267 |
+
body=True,
|
268 |
+
clothes=False,
|
269 |
+
accessories=False,
|
270 |
+
background=False,
|
271 |
+
confidence=0.2,
|
272 |
+
detail_method="VITMatte(local)",
|
273 |
+
detail_erode=6,
|
274 |
+
detail_dilate=6,
|
275 |
+
black_point=0.1,
|
276 |
+
white_point=0.99,
|
277 |
+
process_detail=True,
|
278 |
+
device="cuda",
|
279 |
+
max_megapixels=2,
|
280 |
+
images=get_value_at_index(loadimage_120, 0),
|
281 |
+
)
|
282 |
+
)
|
283 |
+
|
284 |
+
setlatentnoisemask_38 = setlatentnoisemask.set_mask(
|
285 |
+
samples=get_value_at_index(vaeencode_37, 0),
|
286 |
+
mask=get_value_at_index(layermask_personmaskultra_v2_28, 1),
|
287 |
+
)
|
288 |
+
|
289 |
+
ksampler_41 = ksampler.sample(
|
290 |
+
seed=random.randint(1, 2**64),
|
291 |
+
steps=30,
|
292 |
+
cfg=0.7000000000000001,
|
293 |
+
sampler_name="dpmpp_2m",
|
294 |
+
scheduler="karras",
|
295 |
+
denoise=0.3,
|
296 |
+
model=get_value_at_index(loraloader_133, 0),
|
297 |
+
positive=get_value_at_index(cliptextencode_113, 0),
|
298 |
+
negative=get_value_at_index(cliptextencode_35, 0),
|
299 |
+
latent_image=get_value_at_index(setlatentnoisemask_38, 0),
|
300 |
+
)
|
301 |
+
|
302 |
+
vaedecode_39 = vaedecode.decode(
|
303 |
+
samples=get_value_at_index(ksampler_41, 0),
|
304 |
+
vae=get_value_at_index(checkpointloadersimple_31, 2),
|
305 |
+
)
|
306 |
+
|
307 |
+
maskpreview_57 = maskpreview.execute(
|
308 |
+
mask=get_value_at_index(layermask_personmaskultra_v2_28, 1)
|
309 |
+
)
|
310 |
+
|
311 |
+
faceparsefaceparsing_58 = faceparsefaceparsing.main(
|
312 |
+
model=get_value_at_index(faceparsingmodelloaderfaceparsing_59, 0),
|
313 |
+
processor=get_value_at_index(
|
314 |
+
faceparsingprocessorloaderfaceparsing_60, 0
|
315 |
+
),
|
316 |
+
image=get_value_at_index(vaedecode_39, 0),
|
317 |
+
)
|
318 |
+
|
319 |
+
faceparsingresultsparserfaceparsing_62 = (
|
320 |
+
faceparsingresultsparserfaceparsing.main(
|
321 |
+
background=False,
|
322 |
+
skin=False,
|
323 |
+
nose=False,
|
324 |
+
eye_g=False,
|
325 |
+
r_eye=True,
|
326 |
+
l_eye=True,
|
327 |
+
r_brow=False,
|
328 |
+
l_brow=False,
|
329 |
+
r_ear=False,
|
330 |
+
l_ear=False,
|
331 |
+
mouth=True,
|
332 |
+
u_lip=True,
|
333 |
+
l_lip=True,
|
334 |
+
hair=False,
|
335 |
+
hat=False,
|
336 |
+
ear_r=False,
|
337 |
+
neck_l=False,
|
338 |
+
neck=False,
|
339 |
+
cloth=False,
|
340 |
+
result=get_value_at_index(faceparsefaceparsing_58, 1),
|
341 |
+
)
|
342 |
+
)
|
343 |
+
|
344 |
+
growmaskwithblur_66 = growmaskwithblur.expand_mask(
|
345 |
+
expand=15,
|
346 |
+
incremental_expandrate=0,
|
347 |
+
tapered_corners=True,
|
348 |
+
flip_input=False,
|
349 |
+
blur_radius=4,
|
350 |
+
lerp_alpha=1,
|
351 |
+
decay_factor=1,
|
352 |
+
fill_holes=False,
|
353 |
+
mask=get_value_at_index(faceparsingresultsparserfaceparsing_62, 0),
|
354 |
+
)
|
355 |
+
|
356 |
+
masktoimage_84 = masktoimage.mask_to_image(
|
357 |
+
mask=get_value_at_index(growmaskwithblur_66, 0)
|
358 |
+
)
|
359 |
+
|
360 |
+
cut_by_mask_82 = cut_by_mask.cut(
|
361 |
+
force_resize_width=0,
|
362 |
+
force_resize_height=0,
|
363 |
+
image=get_value_at_index(vaedecode_39, 0),
|
364 |
+
mask=get_value_at_index(masktoimage_84, 0),
|
365 |
+
)
|
366 |
+
|
367 |
+
imagecompositemasked_86 = imagecompositemasked.composite(
|
368 |
+
x=0,
|
369 |
+
y=0,
|
370 |
+
resize_source=False,
|
371 |
+
destination=get_value_at_index(vaedecode_39, 0),
|
372 |
+
mask=get_value_at_index(growmaskwithblur_66, 0),
|
373 |
+
source=get_value_at_index(loadimage_120, 0),
|
374 |
+
)
|
375 |
+
|
376 |
+
saveimage_114 = saveimage.save_images(
|
377 |
+
filename_prefix="ComfyUI",
|
378 |
+
images=get_value_at_index(imagecompositemasked_86, 0),
|
379 |
+
)
|
380 |
+
saved_path = f"output/{saveimage_114['ui']['images'][0]['filename']}"
|
381 |
+
|
382 |
+
return saved_path
|
383 |
+
|
384 |
+
anything_everywhere_116 = anything_everywhere.func(
|
385 |
+
IMAGE=get_value_at_index(loadimage_120, 0)
|
386 |
+
)
|
387 |
+
|
388 |
+
if __name__ == "__main__":
|
389 |
+
with gr.Blocks(theme=gr.themes.Soft()) as app:
|
390 |
+
gr.Markdown("# ✨ Skin Fixing Application ✨")
|
391 |
+
gr.Markdown("Upload a structure image and generate a fixed version.")
|
392 |
+
|
393 |
+
with gr.Row():
|
394 |
+
with gr.Column(scale=1):
|
395 |
+
skin_image = gr.Image(
|
396 |
+
label="AI Skin Image",
|
397 |
+
type="filepath",
|
398 |
+
interactive=True,
|
399 |
+
height=300, # Set a fixed height
|
400 |
+
width=300, # Set a fixed width
|
401 |
+
)
|
402 |
+
generate_btn = gr.Button("Generate", variant="primary")
|
403 |
+
|
404 |
+
with gr.Column(scale=1):
|
405 |
+
output_image = gr.Image(
|
406 |
+
label="Generated Real Skin Image",
|
407 |
+
interactive=False,
|
408 |
+
height=300, # Set a fixed height
|
409 |
+
width=300, # Set a fixed width
|
410 |
+
)
|
411 |
+
|
412 |
+
generate_btn.click(
|
413 |
+
fn=generate_image,
|
414 |
+
inputs=[skin_image],
|
415 |
+
outputs=[output_image]
|
416 |
+
)
|
417 |
+
|
418 |
+
app.launch(share=True)
|
419 |
+
|
420 |
+
|
app/__init__.py
ADDED
File without changes
|
app/app_settings.py
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import json
|
3 |
+
from aiohttp import web
|
4 |
+
|
5 |
+
|
6 |
+
class AppSettings():
|
7 |
+
def __init__(self, user_manager):
|
8 |
+
self.user_manager = user_manager
|
9 |
+
|
10 |
+
def get_settings(self, request):
|
11 |
+
file = self.user_manager.get_request_user_filepath(
|
12 |
+
request, "comfy.settings.json")
|
13 |
+
if os.path.isfile(file):
|
14 |
+
with open(file) as f:
|
15 |
+
return json.load(f)
|
16 |
+
else:
|
17 |
+
return {}
|
18 |
+
|
19 |
+
def save_settings(self, request, settings):
|
20 |
+
file = self.user_manager.get_request_user_filepath(
|
21 |
+
request, "comfy.settings.json")
|
22 |
+
with open(file, "w") as f:
|
23 |
+
f.write(json.dumps(settings, indent=4))
|
24 |
+
|
25 |
+
def add_routes(self, routes):
|
26 |
+
@routes.get("/settings")
|
27 |
+
async def get_settings(request):
|
28 |
+
return web.json_response(self.get_settings(request))
|
29 |
+
|
30 |
+
@routes.get("/settings/{id}")
|
31 |
+
async def get_setting(request):
|
32 |
+
value = None
|
33 |
+
settings = self.get_settings(request)
|
34 |
+
setting_id = request.match_info.get("id", None)
|
35 |
+
if setting_id and setting_id in settings:
|
36 |
+
value = settings[setting_id]
|
37 |
+
return web.json_response(value)
|
38 |
+
|
39 |
+
@routes.post("/settings")
|
40 |
+
async def post_settings(request):
|
41 |
+
settings = self.get_settings(request)
|
42 |
+
new_settings = await request.json()
|
43 |
+
self.save_settings(request, {**settings, **new_settings})
|
44 |
+
return web.Response(status=200)
|
45 |
+
|
46 |
+
@routes.post("/settings/{id}")
|
47 |
+
async def post_setting(request):
|
48 |
+
setting_id = request.match_info.get("id", None)
|
49 |
+
if not setting_id:
|
50 |
+
return web.Response(status=400)
|
51 |
+
settings = self.get_settings(request)
|
52 |
+
settings[setting_id] = await request.json()
|
53 |
+
self.save_settings(request, settings)
|
54 |
+
return web.Response(status=200)
|
app/frontend_management.py
ADDED
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
import argparse
|
3 |
+
import logging
|
4 |
+
import os
|
5 |
+
import re
|
6 |
+
import tempfile
|
7 |
+
import zipfile
|
8 |
+
from dataclasses import dataclass
|
9 |
+
from functools import cached_property
|
10 |
+
from pathlib import Path
|
11 |
+
from typing import TypedDict
|
12 |
+
|
13 |
+
import requests
|
14 |
+
from typing_extensions import NotRequired
|
15 |
+
from comfy.cli_args import DEFAULT_VERSION_STRING
|
16 |
+
|
17 |
+
|
18 |
+
REQUEST_TIMEOUT = 10 # seconds
|
19 |
+
|
20 |
+
|
21 |
+
class Asset(TypedDict):
|
22 |
+
url: str
|
23 |
+
|
24 |
+
|
25 |
+
class Release(TypedDict):
|
26 |
+
id: int
|
27 |
+
tag_name: str
|
28 |
+
name: str
|
29 |
+
prerelease: bool
|
30 |
+
created_at: str
|
31 |
+
published_at: str
|
32 |
+
body: str
|
33 |
+
assets: NotRequired[list[Asset]]
|
34 |
+
|
35 |
+
|
36 |
+
@dataclass
|
37 |
+
class FrontEndProvider:
|
38 |
+
owner: str
|
39 |
+
repo: str
|
40 |
+
|
41 |
+
@property
|
42 |
+
def folder_name(self) -> str:
|
43 |
+
return f"{self.owner}_{self.repo}"
|
44 |
+
|
45 |
+
@property
|
46 |
+
def release_url(self) -> str:
|
47 |
+
return f"https://api.github.com/repos/{self.owner}/{self.repo}/releases"
|
48 |
+
|
49 |
+
@cached_property
|
50 |
+
def all_releases(self) -> list[Release]:
|
51 |
+
releases = []
|
52 |
+
api_url = self.release_url
|
53 |
+
while api_url:
|
54 |
+
response = requests.get(api_url, timeout=REQUEST_TIMEOUT)
|
55 |
+
response.raise_for_status() # Raises an HTTPError if the response was an error
|
56 |
+
releases.extend(response.json())
|
57 |
+
# GitHub uses the Link header to provide pagination links. Check if it exists and update api_url accordingly.
|
58 |
+
if "next" in response.links:
|
59 |
+
api_url = response.links["next"]["url"]
|
60 |
+
else:
|
61 |
+
api_url = None
|
62 |
+
return releases
|
63 |
+
|
64 |
+
@cached_property
|
65 |
+
def latest_release(self) -> Release:
|
66 |
+
latest_release_url = f"{self.release_url}/latest"
|
67 |
+
response = requests.get(latest_release_url, timeout=REQUEST_TIMEOUT)
|
68 |
+
response.raise_for_status() # Raises an HTTPError if the response was an error
|
69 |
+
return response.json()
|
70 |
+
|
71 |
+
def get_release(self, version: str) -> Release:
|
72 |
+
if version == "latest":
|
73 |
+
return self.latest_release
|
74 |
+
else:
|
75 |
+
for release in self.all_releases:
|
76 |
+
if release["tag_name"] in [version, f"v{version}"]:
|
77 |
+
return release
|
78 |
+
raise ValueError(f"Version {version} not found in releases")
|
79 |
+
|
80 |
+
|
81 |
+
def download_release_asset_zip(release: Release, destination_path: str) -> None:
|
82 |
+
"""Download dist.zip from github release."""
|
83 |
+
asset_url = None
|
84 |
+
for asset in release.get("assets", []):
|
85 |
+
if asset["name"] == "dist.zip":
|
86 |
+
asset_url = asset["url"]
|
87 |
+
break
|
88 |
+
|
89 |
+
if not asset_url:
|
90 |
+
raise ValueError("dist.zip not found in the release assets")
|
91 |
+
|
92 |
+
# Use a temporary file to download the zip content
|
93 |
+
with tempfile.TemporaryFile() as tmp_file:
|
94 |
+
headers = {"Accept": "application/octet-stream"}
|
95 |
+
response = requests.get(
|
96 |
+
asset_url, headers=headers, allow_redirects=True, timeout=REQUEST_TIMEOUT
|
97 |
+
)
|
98 |
+
response.raise_for_status() # Ensure we got a successful response
|
99 |
+
|
100 |
+
# Write the content to the temporary file
|
101 |
+
tmp_file.write(response.content)
|
102 |
+
|
103 |
+
# Go back to the beginning of the temporary file
|
104 |
+
tmp_file.seek(0)
|
105 |
+
|
106 |
+
# Extract the zip file content to the destination path
|
107 |
+
with zipfile.ZipFile(tmp_file, "r") as zip_ref:
|
108 |
+
zip_ref.extractall(destination_path)
|
109 |
+
|
110 |
+
|
111 |
+
class FrontendManager:
|
112 |
+
DEFAULT_FRONTEND_PATH = str(Path(__file__).parents[1] / "web")
|
113 |
+
CUSTOM_FRONTENDS_ROOT = str(Path(__file__).parents[1] / "web_custom_versions")
|
114 |
+
|
115 |
+
@classmethod
|
116 |
+
def parse_version_string(cls, value: str) -> tuple[str, str, str]:
|
117 |
+
"""
|
118 |
+
Args:
|
119 |
+
value (str): The version string to parse.
|
120 |
+
|
121 |
+
Returns:
|
122 |
+
tuple[str, str]: A tuple containing provider name and version.
|
123 |
+
|
124 |
+
Raises:
|
125 |
+
argparse.ArgumentTypeError: If the version string is invalid.
|
126 |
+
"""
|
127 |
+
VERSION_PATTERN = r"^([a-zA-Z0-9][a-zA-Z0-9-]{0,38})/([a-zA-Z0-9_.-]+)@(v?\d+\.\d+\.\d+|latest)$"
|
128 |
+
match_result = re.match(VERSION_PATTERN, value)
|
129 |
+
if match_result is None:
|
130 |
+
raise argparse.ArgumentTypeError(f"Invalid version string: {value}")
|
131 |
+
|
132 |
+
return match_result.group(1), match_result.group(2), match_result.group(3)
|
133 |
+
|
134 |
+
@classmethod
|
135 |
+
def init_frontend_unsafe(cls, version_string: str) -> str:
|
136 |
+
"""
|
137 |
+
Initializes the frontend for the specified version.
|
138 |
+
|
139 |
+
Args:
|
140 |
+
version_string (str): The version string.
|
141 |
+
|
142 |
+
Returns:
|
143 |
+
str: The path to the initialized frontend.
|
144 |
+
|
145 |
+
Raises:
|
146 |
+
Exception: If there is an error during the initialization process.
|
147 |
+
main error source might be request timeout or invalid URL.
|
148 |
+
"""
|
149 |
+
if version_string == DEFAULT_VERSION_STRING:
|
150 |
+
return cls.DEFAULT_FRONTEND_PATH
|
151 |
+
|
152 |
+
repo_owner, repo_name, version = cls.parse_version_string(version_string)
|
153 |
+
provider = FrontEndProvider(repo_owner, repo_name)
|
154 |
+
release = provider.get_release(version)
|
155 |
+
|
156 |
+
semantic_version = release["tag_name"].lstrip("v")
|
157 |
+
web_root = str(
|
158 |
+
Path(cls.CUSTOM_FRONTENDS_ROOT) / provider.folder_name / semantic_version
|
159 |
+
)
|
160 |
+
if not os.path.exists(web_root):
|
161 |
+
os.makedirs(web_root, exist_ok=True)
|
162 |
+
logging.info(
|
163 |
+
"Downloading frontend(%s) version(%s) to (%s)",
|
164 |
+
provider.folder_name,
|
165 |
+
semantic_version,
|
166 |
+
web_root,
|
167 |
+
)
|
168 |
+
logging.debug(release)
|
169 |
+
download_release_asset_zip(release, destination_path=web_root)
|
170 |
+
return web_root
|
171 |
+
|
172 |
+
@classmethod
|
173 |
+
def init_frontend(cls, version_string: str) -> str:
|
174 |
+
"""
|
175 |
+
Initializes the frontend with the specified version string.
|
176 |
+
|
177 |
+
Args:
|
178 |
+
version_string (str): The version string to initialize the frontend with.
|
179 |
+
|
180 |
+
Returns:
|
181 |
+
str: The path of the initialized frontend.
|
182 |
+
"""
|
183 |
+
try:
|
184 |
+
return cls.init_frontend_unsafe(version_string)
|
185 |
+
except Exception as e:
|
186 |
+
logging.error("Failed to initialize frontend: %s", e)
|
187 |
+
logging.info("Falling back to the default frontend.")
|
188 |
+
return cls.DEFAULT_FRONTEND_PATH
|
app/user_manager.py
ADDED
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import os
|
3 |
+
import re
|
4 |
+
import uuid
|
5 |
+
import glob
|
6 |
+
import shutil
|
7 |
+
from aiohttp import web
|
8 |
+
from comfy.cli_args import args
|
9 |
+
from folder_paths import user_directory
|
10 |
+
from .app_settings import AppSettings
|
11 |
+
|
12 |
+
default_user = "default"
|
13 |
+
users_file = os.path.join(user_directory, "users.json")
|
14 |
+
|
15 |
+
|
16 |
+
class UserManager():
|
17 |
+
def __init__(self):
|
18 |
+
global user_directory
|
19 |
+
|
20 |
+
self.settings = AppSettings(self)
|
21 |
+
if not os.path.exists(user_directory):
|
22 |
+
os.mkdir(user_directory)
|
23 |
+
if not args.multi_user:
|
24 |
+
print("****** User settings have been changed to be stored on the server instead of browser storage. ******")
|
25 |
+
print("****** For multi-user setups add the --multi-user CLI argument to enable multiple user profiles. ******")
|
26 |
+
|
27 |
+
if args.multi_user:
|
28 |
+
if os.path.isfile(users_file):
|
29 |
+
with open(users_file) as f:
|
30 |
+
self.users = json.load(f)
|
31 |
+
else:
|
32 |
+
self.users = {}
|
33 |
+
else:
|
34 |
+
self.users = {"default": "default"}
|
35 |
+
|
36 |
+
def get_request_user_id(self, request):
|
37 |
+
user = "default"
|
38 |
+
if args.multi_user and "comfy-user" in request.headers:
|
39 |
+
user = request.headers["comfy-user"]
|
40 |
+
|
41 |
+
if user not in self.users:
|
42 |
+
raise KeyError("Unknown user: " + user)
|
43 |
+
|
44 |
+
return user
|
45 |
+
|
46 |
+
def get_request_user_filepath(self, request, file, type="userdata", create_dir=True):
|
47 |
+
global user_directory
|
48 |
+
|
49 |
+
if type == "userdata":
|
50 |
+
root_dir = user_directory
|
51 |
+
else:
|
52 |
+
raise KeyError("Unknown filepath type:" + type)
|
53 |
+
|
54 |
+
user = self.get_request_user_id(request)
|
55 |
+
path = user_root = os.path.abspath(os.path.join(root_dir, user))
|
56 |
+
|
57 |
+
# prevent leaving /{type}
|
58 |
+
if os.path.commonpath((root_dir, user_root)) != root_dir:
|
59 |
+
return None
|
60 |
+
|
61 |
+
if file is not None:
|
62 |
+
# prevent leaving /{type}/{user}
|
63 |
+
path = os.path.abspath(os.path.join(user_root, file))
|
64 |
+
if os.path.commonpath((user_root, path)) != user_root:
|
65 |
+
return None
|
66 |
+
|
67 |
+
parent = os.path.split(path)[0]
|
68 |
+
|
69 |
+
if create_dir and not os.path.exists(parent):
|
70 |
+
os.makedirs(parent, exist_ok=True)
|
71 |
+
|
72 |
+
return path
|
73 |
+
|
74 |
+
def add_user(self, name):
|
75 |
+
name = name.strip()
|
76 |
+
if not name:
|
77 |
+
raise ValueError("username not provided")
|
78 |
+
user_id = re.sub("[^a-zA-Z0-9-_]+", '-', name)
|
79 |
+
user_id = user_id + "_" + str(uuid.uuid4())
|
80 |
+
|
81 |
+
self.users[user_id] = name
|
82 |
+
|
83 |
+
global users_file
|
84 |
+
with open(users_file, "w") as f:
|
85 |
+
json.dump(self.users, f)
|
86 |
+
|
87 |
+
return user_id
|
88 |
+
|
89 |
+
def add_routes(self, routes):
|
90 |
+
self.settings.add_routes(routes)
|
91 |
+
|
92 |
+
@routes.get("/users")
|
93 |
+
async def get_users(request):
|
94 |
+
if args.multi_user:
|
95 |
+
return web.json_response({"storage": "server", "users": self.users})
|
96 |
+
else:
|
97 |
+
user_dir = self.get_request_user_filepath(request, None, create_dir=False)
|
98 |
+
return web.json_response({
|
99 |
+
"storage": "server",
|
100 |
+
"migrated": os.path.exists(user_dir)
|
101 |
+
})
|
102 |
+
|
103 |
+
@routes.post("/users")
|
104 |
+
async def post_users(request):
|
105 |
+
body = await request.json()
|
106 |
+
username = body["username"]
|
107 |
+
if username in self.users.values():
|
108 |
+
return web.json_response({"error": "Duplicate username."}, status=400)
|
109 |
+
|
110 |
+
user_id = self.add_user(username)
|
111 |
+
return web.json_response(user_id)
|
112 |
+
|
113 |
+
@routes.get("/userdata")
|
114 |
+
async def listuserdata(request):
|
115 |
+
directory = request.rel_url.query.get('dir', '')
|
116 |
+
if not directory:
|
117 |
+
return web.Response(status=400)
|
118 |
+
|
119 |
+
path = self.get_request_user_filepath(request, directory)
|
120 |
+
if not path:
|
121 |
+
return web.Response(status=403)
|
122 |
+
|
123 |
+
if not os.path.exists(path):
|
124 |
+
return web.Response(status=404)
|
125 |
+
|
126 |
+
recurse = request.rel_url.query.get('recurse', '').lower() == "true"
|
127 |
+
results = glob.glob(os.path.join(
|
128 |
+
glob.escape(path), '**/*'), recursive=recurse)
|
129 |
+
results = [os.path.relpath(x, path) for x in results if os.path.isfile(x)]
|
130 |
+
|
131 |
+
split_path = request.rel_url.query.get('split', '').lower() == "true"
|
132 |
+
if split_path:
|
133 |
+
results = [[x] + x.split(os.sep) for x in results]
|
134 |
+
|
135 |
+
return web.json_response(results)
|
136 |
+
|
137 |
+
def get_user_data_path(request, check_exists = False, param = "file"):
|
138 |
+
file = request.match_info.get(param, None)
|
139 |
+
if not file:
|
140 |
+
return web.Response(status=400)
|
141 |
+
|
142 |
+
path = self.get_request_user_filepath(request, file)
|
143 |
+
if not path:
|
144 |
+
return web.Response(status=403)
|
145 |
+
|
146 |
+
if check_exists and not os.path.exists(path):
|
147 |
+
return web.Response(status=404)
|
148 |
+
|
149 |
+
return path
|
150 |
+
|
151 |
+
@routes.get("/userdata/{file}")
|
152 |
+
async def getuserdata(request):
|
153 |
+
path = get_user_data_path(request, check_exists=True)
|
154 |
+
if not isinstance(path, str):
|
155 |
+
return path
|
156 |
+
|
157 |
+
return web.FileResponse(path)
|
158 |
+
|
159 |
+
@routes.post("/userdata/{file}")
|
160 |
+
async def post_userdata(request):
|
161 |
+
path = get_user_data_path(request)
|
162 |
+
if not isinstance(path, str):
|
163 |
+
return path
|
164 |
+
|
165 |
+
overwrite = request.query["overwrite"] != "false"
|
166 |
+
if not overwrite and os.path.exists(path):
|
167 |
+
return web.Response(status=409)
|
168 |
+
|
169 |
+
body = await request.read()
|
170 |
+
|
171 |
+
with open(path, "wb") as f:
|
172 |
+
f.write(body)
|
173 |
+
|
174 |
+
resp = os.path.relpath(path, self.get_request_user_filepath(request, None))
|
175 |
+
return web.json_response(resp)
|
176 |
+
|
177 |
+
@routes.delete("/userdata/{file}")
|
178 |
+
async def delete_userdata(request):
|
179 |
+
path = get_user_data_path(request, check_exists=True)
|
180 |
+
if not isinstance(path, str):
|
181 |
+
return path
|
182 |
+
|
183 |
+
os.remove(path)
|
184 |
+
|
185 |
+
return web.Response(status=204)
|
186 |
+
|
187 |
+
@routes.post("/userdata/{file}/move/{dest}")
|
188 |
+
async def move_userdata(request):
|
189 |
+
source = get_user_data_path(request, check_exists=True)
|
190 |
+
if not isinstance(source, str):
|
191 |
+
return source
|
192 |
+
|
193 |
+
dest = get_user_data_path(request, check_exists=False, param="dest")
|
194 |
+
if not isinstance(source, str):
|
195 |
+
return dest
|
196 |
+
|
197 |
+
overwrite = request.query["overwrite"] != "false"
|
198 |
+
if not overwrite and os.path.exists(dest):
|
199 |
+
return web.Response(status=409)
|
200 |
+
|
201 |
+
print(f"moving '{source}' -> '{dest}'")
|
202 |
+
shutil.move(source, dest)
|
203 |
+
|
204 |
+
resp = os.path.relpath(dest, self.get_request_user_filepath(request, None))
|
205 |
+
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,437 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#taken from: https://github.com/lllyasviel/ControlNet
|
2 |
+
#and modified
|
3 |
+
|
4 |
+
import torch
|
5 |
+
import torch as th
|
6 |
+
import torch.nn as nn
|
7 |
+
|
8 |
+
from ..ldm.modules.diffusionmodules.util import (
|
9 |
+
zero_module,
|
10 |
+
timestep_embedding,
|
11 |
+
)
|
12 |
+
|
13 |
+
from ..ldm.modules.attention import SpatialTransformer
|
14 |
+
from ..ldm.modules.diffusionmodules.openaimodel import UNetModel, TimestepEmbedSequential, ResBlock, Downsample
|
15 |
+
from ..ldm.util import exists
|
16 |
+
from .control_types import UNION_CONTROLNET_TYPES
|
17 |
+
from collections import OrderedDict
|
18 |
+
import comfy.ops
|
19 |
+
from comfy.ldm.modules.attention import optimized_attention
|
20 |
+
|
21 |
+
class OptimizedAttention(nn.Module):
|
22 |
+
def __init__(self, c, nhead, dropout=0.0, dtype=None, device=None, operations=None):
|
23 |
+
super().__init__()
|
24 |
+
self.heads = nhead
|
25 |
+
self.c = c
|
26 |
+
|
27 |
+
self.in_proj = operations.Linear(c, c * 3, bias=True, dtype=dtype, device=device)
|
28 |
+
self.out_proj = operations.Linear(c, c, bias=True, dtype=dtype, device=device)
|
29 |
+
|
30 |
+
def forward(self, x):
|
31 |
+
x = self.in_proj(x)
|
32 |
+
q, k, v = x.split(self.c, dim=2)
|
33 |
+
out = optimized_attention(q, k, v, self.heads)
|
34 |
+
return self.out_proj(out)
|
35 |
+
|
36 |
+
class QuickGELU(nn.Module):
|
37 |
+
def forward(self, x: torch.Tensor):
|
38 |
+
return x * torch.sigmoid(1.702 * x)
|
39 |
+
|
40 |
+
class ResBlockUnionControlnet(nn.Module):
|
41 |
+
def __init__(self, dim, nhead, dtype=None, device=None, operations=None):
|
42 |
+
super().__init__()
|
43 |
+
self.attn = OptimizedAttention(dim, nhead, dtype=dtype, device=device, operations=operations)
|
44 |
+
self.ln_1 = operations.LayerNorm(dim, dtype=dtype, device=device)
|
45 |
+
self.mlp = nn.Sequential(
|
46 |
+
OrderedDict([("c_fc", operations.Linear(dim, dim * 4, dtype=dtype, device=device)), ("gelu", QuickGELU()),
|
47 |
+
("c_proj", operations.Linear(dim * 4, dim, dtype=dtype, device=device))]))
|
48 |
+
self.ln_2 = operations.LayerNorm(dim, dtype=dtype, device=device)
|
49 |
+
|
50 |
+
def attention(self, x: torch.Tensor):
|
51 |
+
return self.attn(x)
|
52 |
+
|
53 |
+
def forward(self, x: torch.Tensor):
|
54 |
+
x = x + self.attention(self.ln_1(x))
|
55 |
+
x = x + self.mlp(self.ln_2(x))
|
56 |
+
return x
|
57 |
+
|
58 |
+
class ControlledUnetModel(UNetModel):
|
59 |
+
#implemented in the ldm unet
|
60 |
+
pass
|
61 |
+
|
62 |
+
class ControlNet(nn.Module):
|
63 |
+
def __init__(
|
64 |
+
self,
|
65 |
+
image_size,
|
66 |
+
in_channels,
|
67 |
+
model_channels,
|
68 |
+
hint_channels,
|
69 |
+
num_res_blocks,
|
70 |
+
dropout=0,
|
71 |
+
channel_mult=(1, 2, 4, 8),
|
72 |
+
conv_resample=True,
|
73 |
+
dims=2,
|
74 |
+
num_classes=None,
|
75 |
+
use_checkpoint=False,
|
76 |
+
dtype=torch.float32,
|
77 |
+
num_heads=-1,
|
78 |
+
num_head_channels=-1,
|
79 |
+
num_heads_upsample=-1,
|
80 |
+
use_scale_shift_norm=False,
|
81 |
+
resblock_updown=False,
|
82 |
+
use_new_attention_order=False,
|
83 |
+
use_spatial_transformer=False, # custom transformer support
|
84 |
+
transformer_depth=1, # custom transformer support
|
85 |
+
context_dim=None, # custom transformer support
|
86 |
+
n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model
|
87 |
+
legacy=True,
|
88 |
+
disable_self_attentions=None,
|
89 |
+
num_attention_blocks=None,
|
90 |
+
disable_middle_self_attn=False,
|
91 |
+
use_linear_in_transformer=False,
|
92 |
+
adm_in_channels=None,
|
93 |
+
transformer_depth_middle=None,
|
94 |
+
transformer_depth_output=None,
|
95 |
+
attn_precision=None,
|
96 |
+
union_controlnet_num_control_type=None,
|
97 |
+
device=None,
|
98 |
+
operations=comfy.ops.disable_weight_init,
|
99 |
+
**kwargs,
|
100 |
+
):
|
101 |
+
super().__init__()
|
102 |
+
assert use_spatial_transformer == True, "use_spatial_transformer has to be true"
|
103 |
+
if use_spatial_transformer:
|
104 |
+
assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...'
|
105 |
+
|
106 |
+
if context_dim is not None:
|
107 |
+
assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...'
|
108 |
+
# from omegaconf.listconfig import ListConfig
|
109 |
+
# if type(context_dim) == ListConfig:
|
110 |
+
# context_dim = list(context_dim)
|
111 |
+
|
112 |
+
if num_heads_upsample == -1:
|
113 |
+
num_heads_upsample = num_heads
|
114 |
+
|
115 |
+
if num_heads == -1:
|
116 |
+
assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set'
|
117 |
+
|
118 |
+
if num_head_channels == -1:
|
119 |
+
assert num_heads != -1, 'Either num_heads or num_head_channels has to be set'
|
120 |
+
|
121 |
+
self.dims = dims
|
122 |
+
self.image_size = image_size
|
123 |
+
self.in_channels = in_channels
|
124 |
+
self.model_channels = model_channels
|
125 |
+
|
126 |
+
if isinstance(num_res_blocks, int):
|
127 |
+
self.num_res_blocks = len(channel_mult) * [num_res_blocks]
|
128 |
+
else:
|
129 |
+
if len(num_res_blocks) != len(channel_mult):
|
130 |
+
raise ValueError("provide num_res_blocks either as an int (globally constant) or "
|
131 |
+
"as a list/tuple (per-level) with the same length as channel_mult")
|
132 |
+
self.num_res_blocks = num_res_blocks
|
133 |
+
|
134 |
+
if disable_self_attentions is not None:
|
135 |
+
# should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not
|
136 |
+
assert len(disable_self_attentions) == len(channel_mult)
|
137 |
+
if num_attention_blocks is not None:
|
138 |
+
assert len(num_attention_blocks) == len(self.num_res_blocks)
|
139 |
+
assert all(map(lambda i: self.num_res_blocks[i] >= num_attention_blocks[i], range(len(num_attention_blocks))))
|
140 |
+
|
141 |
+
transformer_depth = transformer_depth[:]
|
142 |
+
|
143 |
+
self.dropout = dropout
|
144 |
+
self.channel_mult = channel_mult
|
145 |
+
self.conv_resample = conv_resample
|
146 |
+
self.num_classes = num_classes
|
147 |
+
self.use_checkpoint = use_checkpoint
|
148 |
+
self.dtype = dtype
|
149 |
+
self.num_heads = num_heads
|
150 |
+
self.num_head_channels = num_head_channels
|
151 |
+
self.num_heads_upsample = num_heads_upsample
|
152 |
+
self.predict_codebook_ids = n_embed is not None
|
153 |
+
|
154 |
+
time_embed_dim = model_channels * 4
|
155 |
+
self.time_embed = nn.Sequential(
|
156 |
+
operations.Linear(model_channels, time_embed_dim, dtype=self.dtype, device=device),
|
157 |
+
nn.SiLU(),
|
158 |
+
operations.Linear(time_embed_dim, time_embed_dim, dtype=self.dtype, device=device),
|
159 |
+
)
|
160 |
+
|
161 |
+
if self.num_classes is not None:
|
162 |
+
if isinstance(self.num_classes, int):
|
163 |
+
self.label_emb = nn.Embedding(num_classes, time_embed_dim)
|
164 |
+
elif self.num_classes == "continuous":
|
165 |
+
print("setting up linear c_adm embedding layer")
|
166 |
+
self.label_emb = nn.Linear(1, time_embed_dim)
|
167 |
+
elif self.num_classes == "sequential":
|
168 |
+
assert adm_in_channels is not None
|
169 |
+
self.label_emb = nn.Sequential(
|
170 |
+
nn.Sequential(
|
171 |
+
operations.Linear(adm_in_channels, time_embed_dim, dtype=self.dtype, device=device),
|
172 |
+
nn.SiLU(),
|
173 |
+
operations.Linear(time_embed_dim, time_embed_dim, dtype=self.dtype, device=device),
|
174 |
+
)
|
175 |
+
)
|
176 |
+
else:
|
177 |
+
raise ValueError()
|
178 |
+
|
179 |
+
self.input_blocks = nn.ModuleList(
|
180 |
+
[
|
181 |
+
TimestepEmbedSequential(
|
182 |
+
operations.conv_nd(dims, in_channels, model_channels, 3, padding=1, dtype=self.dtype, device=device)
|
183 |
+
)
|
184 |
+
]
|
185 |
+
)
|
186 |
+
self.zero_convs = nn.ModuleList([self.make_zero_conv(model_channels, operations=operations, dtype=self.dtype, device=device)])
|
187 |
+
|
188 |
+
self.input_hint_block = TimestepEmbedSequential(
|
189 |
+
operations.conv_nd(dims, hint_channels, 16, 3, padding=1, dtype=self.dtype, device=device),
|
190 |
+
nn.SiLU(),
|
191 |
+
operations.conv_nd(dims, 16, 16, 3, padding=1, dtype=self.dtype, device=device),
|
192 |
+
nn.SiLU(),
|
193 |
+
operations.conv_nd(dims, 16, 32, 3, padding=1, stride=2, dtype=self.dtype, device=device),
|
194 |
+
nn.SiLU(),
|
195 |
+
operations.conv_nd(dims, 32, 32, 3, padding=1, dtype=self.dtype, device=device),
|
196 |
+
nn.SiLU(),
|
197 |
+
operations.conv_nd(dims, 32, 96, 3, padding=1, stride=2, dtype=self.dtype, device=device),
|
198 |
+
nn.SiLU(),
|
199 |
+
operations.conv_nd(dims, 96, 96, 3, padding=1, dtype=self.dtype, device=device),
|
200 |
+
nn.SiLU(),
|
201 |
+
operations.conv_nd(dims, 96, 256, 3, padding=1, stride=2, dtype=self.dtype, device=device),
|
202 |
+
nn.SiLU(),
|
203 |
+
operations.conv_nd(dims, 256, model_channels, 3, padding=1, dtype=self.dtype, device=device)
|
204 |
+
)
|
205 |
+
|
206 |
+
self._feature_size = model_channels
|
207 |
+
input_block_chans = [model_channels]
|
208 |
+
ch = model_channels
|
209 |
+
ds = 1
|
210 |
+
for level, mult in enumerate(channel_mult):
|
211 |
+
for nr in range(self.num_res_blocks[level]):
|
212 |
+
layers = [
|
213 |
+
ResBlock(
|
214 |
+
ch,
|
215 |
+
time_embed_dim,
|
216 |
+
dropout,
|
217 |
+
out_channels=mult * model_channels,
|
218 |
+
dims=dims,
|
219 |
+
use_checkpoint=use_checkpoint,
|
220 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
221 |
+
dtype=self.dtype,
|
222 |
+
device=device,
|
223 |
+
operations=operations,
|
224 |
+
)
|
225 |
+
]
|
226 |
+
ch = mult * model_channels
|
227 |
+
num_transformers = transformer_depth.pop(0)
|
228 |
+
if num_transformers > 0:
|
229 |
+
if num_head_channels == -1:
|
230 |
+
dim_head = ch // num_heads
|
231 |
+
else:
|
232 |
+
num_heads = ch // num_head_channels
|
233 |
+
dim_head = num_head_channels
|
234 |
+
if legacy:
|
235 |
+
#num_heads = 1
|
236 |
+
dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
|
237 |
+
if exists(disable_self_attentions):
|
238 |
+
disabled_sa = disable_self_attentions[level]
|
239 |
+
else:
|
240 |
+
disabled_sa = False
|
241 |
+
|
242 |
+
if not exists(num_attention_blocks) or nr < num_attention_blocks[level]:
|
243 |
+
layers.append(
|
244 |
+
SpatialTransformer(
|
245 |
+
ch, num_heads, dim_head, depth=num_transformers, context_dim=context_dim,
|
246 |
+
disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
|
247 |
+
use_checkpoint=use_checkpoint, attn_precision=attn_precision, dtype=self.dtype, device=device, operations=operations
|
248 |
+
)
|
249 |
+
)
|
250 |
+
self.input_blocks.append(TimestepEmbedSequential(*layers))
|
251 |
+
self.zero_convs.append(self.make_zero_conv(ch, operations=operations, dtype=self.dtype, device=device))
|
252 |
+
self._feature_size += ch
|
253 |
+
input_block_chans.append(ch)
|
254 |
+
if level != len(channel_mult) - 1:
|
255 |
+
out_ch = ch
|
256 |
+
self.input_blocks.append(
|
257 |
+
TimestepEmbedSequential(
|
258 |
+
ResBlock(
|
259 |
+
ch,
|
260 |
+
time_embed_dim,
|
261 |
+
dropout,
|
262 |
+
out_channels=out_ch,
|
263 |
+
dims=dims,
|
264 |
+
use_checkpoint=use_checkpoint,
|
265 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
266 |
+
down=True,
|
267 |
+
dtype=self.dtype,
|
268 |
+
device=device,
|
269 |
+
operations=operations
|
270 |
+
)
|
271 |
+
if resblock_updown
|
272 |
+
else Downsample(
|
273 |
+
ch, conv_resample, dims=dims, out_channels=out_ch, dtype=self.dtype, device=device, operations=operations
|
274 |
+
)
|
275 |
+
)
|
276 |
+
)
|
277 |
+
ch = out_ch
|
278 |
+
input_block_chans.append(ch)
|
279 |
+
self.zero_convs.append(self.make_zero_conv(ch, operations=operations, dtype=self.dtype, device=device))
|
280 |
+
ds *= 2
|
281 |
+
self._feature_size += ch
|
282 |
+
|
283 |
+
if num_head_channels == -1:
|
284 |
+
dim_head = ch // num_heads
|
285 |
+
else:
|
286 |
+
num_heads = ch // num_head_channels
|
287 |
+
dim_head = num_head_channels
|
288 |
+
if legacy:
|
289 |
+
#num_heads = 1
|
290 |
+
dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
|
291 |
+
mid_block = [
|
292 |
+
ResBlock(
|
293 |
+
ch,
|
294 |
+
time_embed_dim,
|
295 |
+
dropout,
|
296 |
+
dims=dims,
|
297 |
+
use_checkpoint=use_checkpoint,
|
298 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
299 |
+
dtype=self.dtype,
|
300 |
+
device=device,
|
301 |
+
operations=operations
|
302 |
+
)]
|
303 |
+
if transformer_depth_middle >= 0:
|
304 |
+
mid_block += [SpatialTransformer( # always uses a self-attn
|
305 |
+
ch, num_heads, dim_head, depth=transformer_depth_middle, context_dim=context_dim,
|
306 |
+
disable_self_attn=disable_middle_self_attn, use_linear=use_linear_in_transformer,
|
307 |
+
use_checkpoint=use_checkpoint, attn_precision=attn_precision, dtype=self.dtype, device=device, operations=operations
|
308 |
+
),
|
309 |
+
ResBlock(
|
310 |
+
ch,
|
311 |
+
time_embed_dim,
|
312 |
+
dropout,
|
313 |
+
dims=dims,
|
314 |
+
use_checkpoint=use_checkpoint,
|
315 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
316 |
+
dtype=self.dtype,
|
317 |
+
device=device,
|
318 |
+
operations=operations
|
319 |
+
)]
|
320 |
+
self.middle_block = TimestepEmbedSequential(*mid_block)
|
321 |
+
self.middle_block_out = self.make_zero_conv(ch, operations=operations, dtype=self.dtype, device=device)
|
322 |
+
self._feature_size += ch
|
323 |
+
|
324 |
+
if union_controlnet_num_control_type is not None:
|
325 |
+
self.num_control_type = union_controlnet_num_control_type
|
326 |
+
num_trans_channel = 320
|
327 |
+
num_trans_head = 8
|
328 |
+
num_trans_layer = 1
|
329 |
+
num_proj_channel = 320
|
330 |
+
# task_scale_factor = num_trans_channel ** 0.5
|
331 |
+
self.task_embedding = nn.Parameter(torch.empty(self.num_control_type, num_trans_channel, dtype=self.dtype, device=device))
|
332 |
+
|
333 |
+
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)])
|
334 |
+
self.spatial_ch_projs = operations.Linear(num_trans_channel, num_proj_channel, dtype=self.dtype, device=device)
|
335 |
+
#-----------------------------------------------------------------------------------------------------
|
336 |
+
|
337 |
+
control_add_embed_dim = 256
|
338 |
+
class ControlAddEmbedding(nn.Module):
|
339 |
+
def __init__(self, in_dim, out_dim, num_control_type, dtype=None, device=None, operations=None):
|
340 |
+
super().__init__()
|
341 |
+
self.num_control_type = num_control_type
|
342 |
+
self.in_dim = in_dim
|
343 |
+
self.linear_1 = operations.Linear(in_dim * num_control_type, out_dim, dtype=dtype, device=device)
|
344 |
+
self.linear_2 = operations.Linear(out_dim, out_dim, dtype=dtype, device=device)
|
345 |
+
def forward(self, control_type, dtype, device):
|
346 |
+
c_type = torch.zeros((self.num_control_type,), device=device)
|
347 |
+
c_type[control_type] = 1.0
|
348 |
+
c_type = timestep_embedding(c_type.flatten(), self.in_dim, repeat_only=False).to(dtype).reshape((-1, self.num_control_type * self.in_dim))
|
349 |
+
return self.linear_2(torch.nn.functional.silu(self.linear_1(c_type)))
|
350 |
+
|
351 |
+
self.control_add_embedding = ControlAddEmbedding(control_add_embed_dim, time_embed_dim, self.num_control_type, dtype=self.dtype, device=device, operations=operations)
|
352 |
+
else:
|
353 |
+
self.task_embedding = None
|
354 |
+
self.control_add_embedding = None
|
355 |
+
|
356 |
+
def union_controlnet_merge(self, hint, control_type, emb, context):
|
357 |
+
# Equivalent to: https://github.com/xinsir6/ControlNetPlus/tree/main
|
358 |
+
inputs = []
|
359 |
+
condition_list = []
|
360 |
+
|
361 |
+
for idx in range(min(1, len(control_type))):
|
362 |
+
controlnet_cond = self.input_hint_block(hint[idx], emb, context)
|
363 |
+
feat_seq = torch.mean(controlnet_cond, dim=(2, 3))
|
364 |
+
if idx < len(control_type):
|
365 |
+
feat_seq += self.task_embedding[control_type[idx]].to(dtype=feat_seq.dtype, device=feat_seq.device)
|
366 |
+
|
367 |
+
inputs.append(feat_seq.unsqueeze(1))
|
368 |
+
condition_list.append(controlnet_cond)
|
369 |
+
|
370 |
+
x = torch.cat(inputs, dim=1)
|
371 |
+
x = self.transformer_layes(x)
|
372 |
+
controlnet_cond_fuser = None
|
373 |
+
for idx in range(len(control_type)):
|
374 |
+
alpha = self.spatial_ch_projs(x[:, idx])
|
375 |
+
alpha = alpha.unsqueeze(-1).unsqueeze(-1)
|
376 |
+
o = condition_list[idx] + alpha
|
377 |
+
if controlnet_cond_fuser is None:
|
378 |
+
controlnet_cond_fuser = o
|
379 |
+
else:
|
380 |
+
controlnet_cond_fuser += o
|
381 |
+
return controlnet_cond_fuser
|
382 |
+
|
383 |
+
def make_zero_conv(self, channels, operations=None, dtype=None, device=None):
|
384 |
+
return TimestepEmbedSequential(operations.conv_nd(self.dims, channels, channels, 1, padding=0, dtype=dtype, device=device))
|
385 |
+
|
386 |
+
def forward(self, x, hint, timesteps, context, y=None, **kwargs):
|
387 |
+
t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False).to(x.dtype)
|
388 |
+
emb = self.time_embed(t_emb)
|
389 |
+
|
390 |
+
guided_hint = None
|
391 |
+
if self.control_add_embedding is not None: #Union Controlnet
|
392 |
+
control_type = kwargs.get("control_type", [])
|
393 |
+
|
394 |
+
if any([c >= self.num_control_type for c in control_type]):
|
395 |
+
max_type = max(control_type)
|
396 |
+
max_type_name = {
|
397 |
+
v: k for k, v in UNION_CONTROLNET_TYPES.items()
|
398 |
+
}[max_type]
|
399 |
+
raise ValueError(
|
400 |
+
f"Control type {max_type_name}({max_type}) is out of range for the number of control types" +
|
401 |
+
f"({self.num_control_type}) supported.\n" +
|
402 |
+
"Please consider using the ProMax ControlNet Union model.\n" +
|
403 |
+
"https://huggingface.co/xinsir/controlnet-union-sdxl-1.0/tree/main"
|
404 |
+
)
|
405 |
+
|
406 |
+
emb += self.control_add_embedding(control_type, emb.dtype, emb.device)
|
407 |
+
if len(control_type) > 0:
|
408 |
+
if len(hint.shape) < 5:
|
409 |
+
hint = hint.unsqueeze(dim=0)
|
410 |
+
guided_hint = self.union_controlnet_merge(hint, control_type, emb, context)
|
411 |
+
|
412 |
+
if guided_hint is None:
|
413 |
+
guided_hint = self.input_hint_block(hint, emb, context)
|
414 |
+
|
415 |
+
out_output = []
|
416 |
+
out_middle = []
|
417 |
+
|
418 |
+
hs = []
|
419 |
+
if self.num_classes is not None:
|
420 |
+
assert y.shape[0] == x.shape[0]
|
421 |
+
emb = emb + self.label_emb(y)
|
422 |
+
|
423 |
+
h = x
|
424 |
+
for module, zero_conv in zip(self.input_blocks, self.zero_convs):
|
425 |
+
if guided_hint is not None:
|
426 |
+
h = module(h, emb, context)
|
427 |
+
h += guided_hint
|
428 |
+
guided_hint = None
|
429 |
+
else:
|
430 |
+
h = module(h, emb, context)
|
431 |
+
out_output.append(zero_conv(h, emb, context))
|
432 |
+
|
433 |
+
h = self.middle_block(h, emb, context)
|
434 |
+
out_middle.append(self.middle_block_out(h, emb, context))
|
435 |
+
|
436 |
+
return {"middle": out_middle, "output": out_output}
|
437 |
+
|
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/mmdit.py
ADDED
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from typing import Dict, 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 |
+
dtype = None,
|
10 |
+
device = None,
|
11 |
+
operations = None,
|
12 |
+
**kwargs,
|
13 |
+
):
|
14 |
+
super().__init__(dtype=dtype, device=device, operations=operations, final_layer=False, num_blocks=num_blocks, **kwargs)
|
15 |
+
# controlnet_blocks
|
16 |
+
self.controlnet_blocks = torch.nn.ModuleList([])
|
17 |
+
for _ in range(len(self.joint_blocks)):
|
18 |
+
self.controlnet_blocks.append(operations.Linear(self.hidden_size, self.hidden_size, device=device, dtype=dtype))
|
19 |
+
|
20 |
+
self.pos_embed_input = comfy.ldm.modules.diffusionmodules.mmdit.PatchEmbed(
|
21 |
+
None,
|
22 |
+
self.patch_size,
|
23 |
+
self.in_channels,
|
24 |
+
self.hidden_size,
|
25 |
+
bias=True,
|
26 |
+
strict_img_size=False,
|
27 |
+
dtype=dtype,
|
28 |
+
device=device,
|
29 |
+
operations=operations
|
30 |
+
)
|
31 |
+
|
32 |
+
def forward(
|
33 |
+
self,
|
34 |
+
x: torch.Tensor,
|
35 |
+
timesteps: torch.Tensor,
|
36 |
+
y: Optional[torch.Tensor] = None,
|
37 |
+
context: Optional[torch.Tensor] = None,
|
38 |
+
hint = None,
|
39 |
+
) -> torch.Tensor:
|
40 |
+
|
41 |
+
#weird sd3 controlnet specific stuff
|
42 |
+
y = torch.zeros_like(y)
|
43 |
+
|
44 |
+
if self.context_processor is not None:
|
45 |
+
context = self.context_processor(context)
|
46 |
+
|
47 |
+
hw = x.shape[-2:]
|
48 |
+
x = self.x_embedder(x) + self.cropped_pos_embed(hw, device=x.device).to(dtype=x.dtype, device=x.device)
|
49 |
+
x += self.pos_embed_input(hint)
|
50 |
+
|
51 |
+
c = self.t_embedder(timesteps, dtype=x.dtype)
|
52 |
+
if y is not None and self.y_embedder is not None:
|
53 |
+
y = self.y_embedder(y)
|
54 |
+
c = c + y
|
55 |
+
|
56 |
+
if context is not None:
|
57 |
+
context = self.context_embedder(context)
|
58 |
+
|
59 |
+
output = []
|
60 |
+
|
61 |
+
blocks = len(self.joint_blocks)
|
62 |
+
for i in range(blocks):
|
63 |
+
context, x = self.joint_blocks[i](
|
64 |
+
context,
|
65 |
+
x,
|
66 |
+
c=c,
|
67 |
+
use_checkpoint=self.use_checkpoint,
|
68 |
+
)
|
69 |
+
|
70 |
+
out = self.controlnet_blocks[i](x)
|
71 |
+
count = self.depth // blocks
|
72 |
+
if i == blocks - 1:
|
73 |
+
count -= 1
|
74 |
+
for j in range(count):
|
75 |
+
output.append(out)
|
76 |
+
|
77 |
+
return {"output": output}
|
comfy/cli_args.py
ADDED
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import enum
|
3 |
+
import os
|
4 |
+
from typing import Optional
|
5 |
+
import comfy.options
|
6 |
+
|
7 |
+
|
8 |
+
class EnumAction(argparse.Action):
|
9 |
+
"""
|
10 |
+
Argparse action for handling Enums
|
11 |
+
"""
|
12 |
+
def __init__(self, **kwargs):
|
13 |
+
# Pop off the type value
|
14 |
+
enum_type = kwargs.pop("type", None)
|
15 |
+
|
16 |
+
# Ensure an Enum subclass is provided
|
17 |
+
if enum_type is None:
|
18 |
+
raise ValueError("type must be assigned an Enum when using EnumAction")
|
19 |
+
if not issubclass(enum_type, enum.Enum):
|
20 |
+
raise TypeError("type must be an Enum when using EnumAction")
|
21 |
+
|
22 |
+
# Generate choices from the Enum
|
23 |
+
choices = tuple(e.value for e in enum_type)
|
24 |
+
kwargs.setdefault("choices", choices)
|
25 |
+
kwargs.setdefault("metavar", f"[{','.join(list(choices))}]")
|
26 |
+
|
27 |
+
super(EnumAction, self).__init__(**kwargs)
|
28 |
+
|
29 |
+
self._enum = enum_type
|
30 |
+
|
31 |
+
def __call__(self, parser, namespace, values, option_string=None):
|
32 |
+
# Convert value back into an Enum
|
33 |
+
value = self._enum(values)
|
34 |
+
setattr(namespace, self.dest, value)
|
35 |
+
|
36 |
+
|
37 |
+
parser = argparse.ArgumentParser()
|
38 |
+
|
39 |
+
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). If --listen is provided without an argument, it defaults to 0.0.0.0. (listens on all)")
|
40 |
+
parser.add_argument("--port", type=int, default=8188, help="Set the listen port.")
|
41 |
+
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")
|
42 |
+
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")
|
43 |
+
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 '*'.")
|
44 |
+
parser.add_argument("--max-upload-size", type=float, default=100, help="Set the maximum upload size in MB.")
|
45 |
+
|
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.")
|
48 |
+
parser.add_argument("--temp-directory", type=str, default=None, help="Set the ComfyUI temp directory (default is in the ComfyUI directory).")
|
49 |
+
parser.add_argument("--input-directory", type=str, default=None, help="Set the ComfyUI input 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("--bf16-unet", action="store_true", help="Run the UNET in bf16. This should only be used for testing stuff.")
|
64 |
+
fpunet_group.add_argument("--fp16-unet", action="store_true", help="Store unet weights in fp16.")
|
65 |
+
fpunet_group.add_argument("--fp8_e4m3fn-unet", action="store_true", help="Store unet weights in fp8_e4m3fn.")
|
66 |
+
fpunet_group.add_argument("--fp8_e5m2-unet", action="store_true", help="Store unet weights in fp8_e5m2.")
|
67 |
+
|
68 |
+
fpvae_group = parser.add_mutually_exclusive_group()
|
69 |
+
fpvae_group.add_argument("--fp16-vae", action="store_true", help="Run the VAE in fp16, might cause black images.")
|
70 |
+
fpvae_group.add_argument("--fp32-vae", action="store_true", help="Run the VAE in full precision fp32.")
|
71 |
+
fpvae_group.add_argument("--bf16-vae", action="store_true", help="Run the VAE in bf16.")
|
72 |
+
|
73 |
+
parser.add_argument("--cpu-vae", action="store_true", help="Run the VAE on the CPU.")
|
74 |
+
|
75 |
+
fpte_group = parser.add_mutually_exclusive_group()
|
76 |
+
fpte_group.add_argument("--fp8_e4m3fn-text-enc", action="store_true", help="Store text encoder weights in fp8 (e4m3fn variant).")
|
77 |
+
fpte_group.add_argument("--fp8_e5m2-text-enc", action="store_true", help="Store text encoder weights in fp8 (e5m2 variant).")
|
78 |
+
fpte_group.add_argument("--fp16-text-enc", action="store_true", help="Store text encoder weights in fp16.")
|
79 |
+
fpte_group.add_argument("--fp32-text-enc", action="store_true", help="Store text encoder weights in fp32.")
|
80 |
+
|
81 |
+
parser.add_argument("--force-channels-last", action="store_true", help="Force channels last format when inferencing the models.")
|
82 |
+
|
83 |
+
parser.add_argument("--directml", type=int, nargs="?", metavar="DIRECTML_DEVICE", const=-1, help="Use torch-directml.")
|
84 |
+
|
85 |
+
parser.add_argument("--disable-ipex-optimize", action="store_true", help="Disables ipex.optimize when loading models with Intel GPUs.")
|
86 |
+
|
87 |
+
class LatentPreviewMethod(enum.Enum):
|
88 |
+
NoPreviews = "none"
|
89 |
+
Auto = "auto"
|
90 |
+
Latent2RGB = "latent2rgb"
|
91 |
+
TAESD = "taesd"
|
92 |
+
|
93 |
+
parser.add_argument("--preview-method", type=LatentPreviewMethod, default=LatentPreviewMethod.NoPreviews, help="Default preview method for sampler nodes.", action=EnumAction)
|
94 |
+
|
95 |
+
attn_group = parser.add_mutually_exclusive_group()
|
96 |
+
attn_group.add_argument("--use-split-cross-attention", action="store_true", help="Use the split cross attention optimization. Ignored when xformers is used.")
|
97 |
+
attn_group.add_argument("--use-quad-cross-attention", action="store_true", help="Use the sub-quadratic cross attention optimization . Ignored when xformers is used.")
|
98 |
+
attn_group.add_argument("--use-pytorch-cross-attention", action="store_true", help="Use the new pytorch 2.0 cross attention function.")
|
99 |
+
|
100 |
+
parser.add_argument("--disable-xformers", action="store_true", help="Disable xformers.")
|
101 |
+
|
102 |
+
upcast = parser.add_mutually_exclusive_group()
|
103 |
+
upcast.add_argument("--force-upcast-attention", action="store_true", help="Force enable attention upcasting, please report if it fixes black images.")
|
104 |
+
upcast.add_argument("--dont-upcast-attention", action="store_true", help="Disable all upcasting of attention. Should be unnecessary except for debugging.")
|
105 |
+
|
106 |
+
|
107 |
+
vram_group = parser.add_mutually_exclusive_group()
|
108 |
+
vram_group.add_argument("--gpu-only", action="store_true", help="Store and run everything (text encoders/CLIP models, etc... on the GPU).")
|
109 |
+
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.")
|
110 |
+
vram_group.add_argument("--normalvram", action="store_true", help="Used to force normal vram use if lowvram gets automatically enabled.")
|
111 |
+
vram_group.add_argument("--lowvram", action="store_true", help="Split the unet in parts to use less vram.")
|
112 |
+
vram_group.add_argument("--novram", action="store_true", help="When lowvram isn't enough.")
|
113 |
+
vram_group.add_argument("--cpu", action="store_true", help="To use the CPU for everything (slow).")
|
114 |
+
|
115 |
+
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.")
|
116 |
+
|
117 |
+
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.")
|
118 |
+
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.")
|
119 |
+
|
120 |
+
parser.add_argument("--dont-print-server", action="store_true", help="Don't print server output.")
|
121 |
+
parser.add_argument("--quick-test-for-ci", action="store_true", help="Quick test for CI.")
|
122 |
+
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).")
|
123 |
+
|
124 |
+
parser.add_argument("--disable-metadata", action="store_true", help="Disable saving prompt metadata in files.")
|
125 |
+
parser.add_argument("--disable-all-custom-nodes", action="store_true", help="Disable loading all custom nodes.")
|
126 |
+
|
127 |
+
parser.add_argument("--multi-user", action="store_true", help="Enables per-user storage.")
|
128 |
+
|
129 |
+
parser.add_argument("--verbose", action="store_true", help="Enables more debug prints.")
|
130 |
+
|
131 |
+
# The default built-in provider hosted under web/
|
132 |
+
DEFAULT_VERSION_STRING = "comfyanonymous/ComfyUI@latest"
|
133 |
+
|
134 |
+
parser.add_argument(
|
135 |
+
"--front-end-version",
|
136 |
+
type=str,
|
137 |
+
default=DEFAULT_VERSION_STRING,
|
138 |
+
help="""
|
139 |
+
Specifies the version of the frontend to be used. This command needs internet connectivity to query and
|
140 |
+
download available frontend implementations from GitHub releases.
|
141 |
+
|
142 |
+
The version string should be in the format of:
|
143 |
+
[repoOwner]/[repoName]@[version]
|
144 |
+
where version is one of: "latest" or a valid version number (e.g. "1.0.0")
|
145 |
+
""",
|
146 |
+
)
|
147 |
+
|
148 |
+
def is_valid_directory(path: Optional[str]) -> Optional[str]:
|
149 |
+
"""Validate if the given path is a directory."""
|
150 |
+
if path is None:
|
151 |
+
return None
|
152 |
+
|
153 |
+
if not os.path.isdir(path):
|
154 |
+
raise argparse.ArgumentTypeError(f"{path} is not a valid directory.")
|
155 |
+
return path
|
156 |
+
|
157 |
+
parser.add_argument(
|
158 |
+
"--front-end-root",
|
159 |
+
type=is_valid_directory,
|
160 |
+
default=None,
|
161 |
+
help="The local filesystem path to the directory where the frontend is located. Overrides --front-end-version.",
|
162 |
+
)
|
163 |
+
|
164 |
+
if comfy.options.args_parsing:
|
165 |
+
args = parser.parse_args()
|
166 |
+
else:
|
167 |
+
args = parser.parse_args([])
|
168 |
+
|
169 |
+
if args.windows_standalone_build:
|
170 |
+
args.auto_launch = True
|
171 |
+
|
172 |
+
if args.disable_auto_launch:
|
173 |
+
args.auto_launch = False
|
174 |
+
|
175 |
+
import logging
|
176 |
+
logging_level = logging.INFO
|
177 |
+
if args.verbose:
|
178 |
+
logging_level = logging.DEBUG
|
179 |
+
|
180 |
+
logging.basicConfig(format="%(message)s", level=logging_level)
|
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,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
}
|
27 |
+
|
28 |
+
class CLIPMLP(torch.nn.Module):
|
29 |
+
def __init__(self, embed_dim, intermediate_size, activation, dtype, device, operations):
|
30 |
+
super().__init__()
|
31 |
+
self.fc1 = operations.Linear(embed_dim, intermediate_size, bias=True, dtype=dtype, device=device)
|
32 |
+
self.activation = ACTIVATIONS[activation]
|
33 |
+
self.fc2 = operations.Linear(intermediate_size, embed_dim, bias=True, dtype=dtype, device=device)
|
34 |
+
|
35 |
+
def forward(self, x):
|
36 |
+
x = self.fc1(x)
|
37 |
+
x = self.activation(x)
|
38 |
+
x = self.fc2(x)
|
39 |
+
return x
|
40 |
+
|
41 |
+
class CLIPLayer(torch.nn.Module):
|
42 |
+
def __init__(self, embed_dim, heads, intermediate_size, intermediate_activation, dtype, device, operations):
|
43 |
+
super().__init__()
|
44 |
+
self.layer_norm1 = operations.LayerNorm(embed_dim, dtype=dtype, device=device)
|
45 |
+
self.self_attn = CLIPAttention(embed_dim, heads, dtype, device, operations)
|
46 |
+
self.layer_norm2 = operations.LayerNorm(embed_dim, dtype=dtype, device=device)
|
47 |
+
self.mlp = CLIPMLP(embed_dim, intermediate_size, intermediate_activation, dtype, device, operations)
|
48 |
+
|
49 |
+
def forward(self, x, mask=None, optimized_attention=None):
|
50 |
+
x += self.self_attn(self.layer_norm1(x), mask, optimized_attention)
|
51 |
+
x += self.mlp(self.layer_norm2(x))
|
52 |
+
return x
|
53 |
+
|
54 |
+
|
55 |
+
class CLIPEncoder(torch.nn.Module):
|
56 |
+
def __init__(self, num_layers, embed_dim, heads, intermediate_size, intermediate_activation, dtype, device, operations):
|
57 |
+
super().__init__()
|
58 |
+
self.layers = torch.nn.ModuleList([CLIPLayer(embed_dim, heads, intermediate_size, intermediate_activation, dtype, device, operations) for i in range(num_layers)])
|
59 |
+
|
60 |
+
def forward(self, x, mask=None, intermediate_output=None):
|
61 |
+
optimized_attention = optimized_attention_for_device(x.device, mask=mask is not None, small_input=True)
|
62 |
+
|
63 |
+
if intermediate_output is not None:
|
64 |
+
if intermediate_output < 0:
|
65 |
+
intermediate_output = len(self.layers) + intermediate_output
|
66 |
+
|
67 |
+
intermediate = None
|
68 |
+
for i, l in enumerate(self.layers):
|
69 |
+
x = l(x, mask, optimized_attention)
|
70 |
+
if i == intermediate_output:
|
71 |
+
intermediate = x.clone()
|
72 |
+
return x, intermediate
|
73 |
+
|
74 |
+
class CLIPEmbeddings(torch.nn.Module):
|
75 |
+
def __init__(self, embed_dim, vocab_size=49408, num_positions=77, dtype=None, device=None, operations=None):
|
76 |
+
super().__init__()
|
77 |
+
self.token_embedding = operations.Embedding(vocab_size, embed_dim, dtype=dtype, device=device)
|
78 |
+
self.position_embedding = operations.Embedding(num_positions, embed_dim, dtype=dtype, device=device)
|
79 |
+
|
80 |
+
def forward(self, input_tokens, dtype=torch.float32):
|
81 |
+
return self.token_embedding(input_tokens, out_dtype=dtype) + comfy.ops.cast_to(self.position_embedding.weight, dtype=dtype, device=input_tokens.device)
|
82 |
+
|
83 |
+
|
84 |
+
class CLIPTextModel_(torch.nn.Module):
|
85 |
+
def __init__(self, config_dict, dtype, device, operations):
|
86 |
+
num_layers = config_dict["num_hidden_layers"]
|
87 |
+
embed_dim = config_dict["hidden_size"]
|
88 |
+
heads = config_dict["num_attention_heads"]
|
89 |
+
intermediate_size = config_dict["intermediate_size"]
|
90 |
+
intermediate_activation = config_dict["hidden_act"]
|
91 |
+
self.eos_token_id = config_dict["eos_token_id"]
|
92 |
+
|
93 |
+
super().__init__()
|
94 |
+
self.embeddings = CLIPEmbeddings(embed_dim, dtype=dtype, device=device, operations=operations)
|
95 |
+
self.encoder = CLIPEncoder(num_layers, embed_dim, heads, intermediate_size, intermediate_activation, dtype, device, operations)
|
96 |
+
self.final_layer_norm = operations.LayerNorm(embed_dim, dtype=dtype, device=device)
|
97 |
+
|
98 |
+
def forward(self, input_tokens, attention_mask=None, intermediate_output=None, final_layer_norm_intermediate=True, dtype=torch.float32):
|
99 |
+
x = self.embeddings(input_tokens, dtype=dtype)
|
100 |
+
mask = None
|
101 |
+
if attention_mask is not None:
|
102 |
+
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])
|
103 |
+
mask = mask.masked_fill(mask.to(torch.bool), float("-inf"))
|
104 |
+
|
105 |
+
causal_mask = torch.empty(x.shape[1], x.shape[1], dtype=x.dtype, device=x.device).fill_(float("-inf")).triu_(1)
|
106 |
+
if mask is not None:
|
107 |
+
mask += causal_mask
|
108 |
+
else:
|
109 |
+
mask = causal_mask
|
110 |
+
|
111 |
+
x, i = self.encoder(x, mask=mask, intermediate_output=intermediate_output)
|
112 |
+
x = self.final_layer_norm(x)
|
113 |
+
if i is not None and final_layer_norm_intermediate:
|
114 |
+
i = self.final_layer_norm(i)
|
115 |
+
|
116 |
+
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),]
|
117 |
+
return x, i, pooled_output
|
118 |
+
|
119 |
+
class CLIPTextModel(torch.nn.Module):
|
120 |
+
def __init__(self, config_dict, dtype, device, operations):
|
121 |
+
super().__init__()
|
122 |
+
self.num_layers = config_dict["num_hidden_layers"]
|
123 |
+
self.text_model = CLIPTextModel_(config_dict, dtype, device, operations)
|
124 |
+
embed_dim = config_dict["hidden_size"]
|
125 |
+
self.text_projection = operations.Linear(embed_dim, embed_dim, bias=False, dtype=dtype, device=device)
|
126 |
+
self.text_projection.weight.copy_(torch.eye(embed_dim))
|
127 |
+
self.dtype = dtype
|
128 |
+
|
129 |
+
def get_input_embeddings(self):
|
130 |
+
return self.text_model.embeddings.token_embedding
|
131 |
+
|
132 |
+
def set_input_embeddings(self, embeddings):
|
133 |
+
self.text_model.embeddings.token_embedding = embeddings
|
134 |
+
|
135 |
+
def forward(self, *args, **kwargs):
|
136 |
+
x = self.text_model(*args, **kwargs)
|
137 |
+
out = self.text_projection(x[2])
|
138 |
+
return (x[0], x[1], out, x[2])
|
139 |
+
|
140 |
+
|
141 |
+
class CLIPVisionEmbeddings(torch.nn.Module):
|
142 |
+
def __init__(self, embed_dim, num_channels=3, patch_size=14, image_size=224, dtype=None, device=None, operations=None):
|
143 |
+
super().__init__()
|
144 |
+
self.class_embedding = torch.nn.Parameter(torch.empty(embed_dim, dtype=dtype, device=device))
|
145 |
+
|
146 |
+
self.patch_embedding = operations.Conv2d(
|
147 |
+
in_channels=num_channels,
|
148 |
+
out_channels=embed_dim,
|
149 |
+
kernel_size=patch_size,
|
150 |
+
stride=patch_size,
|
151 |
+
bias=False,
|
152 |
+
dtype=dtype,
|
153 |
+
device=device
|
154 |
+
)
|
155 |
+
|
156 |
+
num_patches = (image_size // patch_size) ** 2
|
157 |
+
num_positions = num_patches + 1
|
158 |
+
self.position_embedding = operations.Embedding(num_positions, embed_dim, dtype=dtype, device=device)
|
159 |
+
|
160 |
+
def forward(self, pixel_values):
|
161 |
+
embeds = self.patch_embedding(pixel_values).flatten(2).transpose(1, 2)
|
162 |
+
return torch.cat([comfy.ops.cast_to_input(self.class_embedding, embeds).expand(pixel_values.shape[0], 1, -1), embeds], dim=1) + comfy.ops.cast_to_input(self.position_embedding.weight, embeds)
|
163 |
+
|
164 |
+
|
165 |
+
class CLIPVision(torch.nn.Module):
|
166 |
+
def __init__(self, config_dict, dtype, device, operations):
|
167 |
+
super().__init__()
|
168 |
+
num_layers = config_dict["num_hidden_layers"]
|
169 |
+
embed_dim = config_dict["hidden_size"]
|
170 |
+
heads = config_dict["num_attention_heads"]
|
171 |
+
intermediate_size = config_dict["intermediate_size"]
|
172 |
+
intermediate_activation = config_dict["hidden_act"]
|
173 |
+
|
174 |
+
self.embeddings = CLIPVisionEmbeddings(embed_dim, config_dict["num_channels"], config_dict["patch_size"], config_dict["image_size"], dtype=dtype, device=device, operations=operations)
|
175 |
+
self.pre_layrnorm = operations.LayerNorm(embed_dim)
|
176 |
+
self.encoder = CLIPEncoder(num_layers, embed_dim, heads, intermediate_size, intermediate_activation, dtype, device, operations)
|
177 |
+
self.post_layernorm = operations.LayerNorm(embed_dim)
|
178 |
+
|
179 |
+
def forward(self, pixel_values, attention_mask=None, intermediate_output=None):
|
180 |
+
x = self.embeddings(pixel_values)
|
181 |
+
x = self.pre_layrnorm(x)
|
182 |
+
#TODO: attention_mask?
|
183 |
+
x, i = self.encoder(x, mask=None, intermediate_output=intermediate_output)
|
184 |
+
pooled_output = self.post_layernorm(x[:, 0, :])
|
185 |
+
return x, i, pooled_output
|
186 |
+
|
187 |
+
class CLIPVisionModelProjection(torch.nn.Module):
|
188 |
+
def __init__(self, config_dict, dtype, device, operations):
|
189 |
+
super().__init__()
|
190 |
+
self.vision_model = CLIPVision(config_dict, dtype, device, operations)
|
191 |
+
self.visual_projection = operations.Linear(config_dict["hidden_size"], config_dict["projection_dim"], bias=False)
|
192 |
+
|
193 |
+
def forward(self, *args, **kwargs):
|
194 |
+
x = self.vision_model(*args, **kwargs)
|
195 |
+
out = self.visual_projection(x[2])
|
196 |
+
return (x[0], x[1], out)
|
comfy/clip_vision.py
ADDED
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
|
13 |
+
class Output:
|
14 |
+
def __getitem__(self, key):
|
15 |
+
return getattr(self, key)
|
16 |
+
def __setitem__(self, key, item):
|
17 |
+
setattr(self, key, item)
|
18 |
+
|
19 |
+
def clip_preprocess(image, size=224):
|
20 |
+
mean = torch.tensor([ 0.48145466,0.4578275,0.40821073], device=image.device, dtype=image.dtype)
|
21 |
+
std = torch.tensor([0.26862954,0.26130258,0.27577711], device=image.device, dtype=image.dtype)
|
22 |
+
image = image.movedim(-1, 1)
|
23 |
+
if not (image.shape[2] == size and image.shape[3] == size):
|
24 |
+
scale = (size / min(image.shape[2], image.shape[3]))
|
25 |
+
image = torch.nn.functional.interpolate(image, size=(round(scale * image.shape[2]), round(scale * image.shape[3])), mode="bicubic", antialias=True)
|
26 |
+
h = (image.shape[2] - size)//2
|
27 |
+
w = (image.shape[3] - size)//2
|
28 |
+
image = image[:,:,h:h+size,w:w+size]
|
29 |
+
image = torch.clip((255. * image), 0, 255).round() / 255.0
|
30 |
+
return (image - mean.view([3,1,1])) / std.view([3,1,1])
|
31 |
+
|
32 |
+
class ClipVisionModel():
|
33 |
+
def __init__(self, json_config):
|
34 |
+
with open(json_config) as f:
|
35 |
+
config = json.load(f)
|
36 |
+
|
37 |
+
self.image_size = config.get("image_size", 224)
|
38 |
+
self.load_device = comfy.model_management.text_encoder_device()
|
39 |
+
offload_device = comfy.model_management.text_encoder_offload_device()
|
40 |
+
self.dtype = comfy.model_management.text_encoder_dtype(self.load_device)
|
41 |
+
self.model = comfy.clip_model.CLIPVisionModelProjection(config, self.dtype, offload_device, comfy.ops.manual_cast)
|
42 |
+
self.model.eval()
|
43 |
+
|
44 |
+
self.patcher = comfy.model_patcher.ModelPatcher(self.model, load_device=self.load_device, offload_device=offload_device)
|
45 |
+
|
46 |
+
def load_sd(self, sd):
|
47 |
+
return self.model.load_state_dict(sd, strict=False)
|
48 |
+
|
49 |
+
def get_sd(self):
|
50 |
+
return self.model.state_dict()
|
51 |
+
|
52 |
+
def encode_image(self, image):
|
53 |
+
comfy.model_management.load_model_gpu(self.patcher)
|
54 |
+
pixel_values = clip_preprocess(image.to(self.load_device), size=self.image_size).float()
|
55 |
+
out = self.model(pixel_values=pixel_values, intermediate_output=-2)
|
56 |
+
|
57 |
+
outputs = Output()
|
58 |
+
outputs["last_hidden_state"] = out[0].to(comfy.model_management.intermediate_device())
|
59 |
+
outputs["image_embeds"] = out[2].to(comfy.model_management.intermediate_device())
|
60 |
+
outputs["penultimate_hidden_states"] = out[1].to(comfy.model_management.intermediate_device())
|
61 |
+
return outputs
|
62 |
+
|
63 |
+
def convert_to_transformers(sd, prefix):
|
64 |
+
sd_k = sd.keys()
|
65 |
+
if "{}transformer.resblocks.0.attn.in_proj_weight".format(prefix) in sd_k:
|
66 |
+
keys_to_replace = {
|
67 |
+
"{}class_embedding".format(prefix): "vision_model.embeddings.class_embedding",
|
68 |
+
"{}conv1.weight".format(prefix): "vision_model.embeddings.patch_embedding.weight",
|
69 |
+
"{}positional_embedding".format(prefix): "vision_model.embeddings.position_embedding.weight",
|
70 |
+
"{}ln_post.bias".format(prefix): "vision_model.post_layernorm.bias",
|
71 |
+
"{}ln_post.weight".format(prefix): "vision_model.post_layernorm.weight",
|
72 |
+
"{}ln_pre.bias".format(prefix): "vision_model.pre_layrnorm.bias",
|
73 |
+
"{}ln_pre.weight".format(prefix): "vision_model.pre_layrnorm.weight",
|
74 |
+
}
|
75 |
+
|
76 |
+
for x in keys_to_replace:
|
77 |
+
if x in sd_k:
|
78 |
+
sd[keys_to_replace[x]] = sd.pop(x)
|
79 |
+
|
80 |
+
if "{}proj".format(prefix) in sd_k:
|
81 |
+
sd['visual_projection.weight'] = sd.pop("{}proj".format(prefix)).transpose(0, 1)
|
82 |
+
|
83 |
+
sd = transformers_convert(sd, prefix, "vision_model.", 48)
|
84 |
+
else:
|
85 |
+
replace_prefix = {prefix: ""}
|
86 |
+
sd = state_dict_prefix_replace(sd, replace_prefix)
|
87 |
+
return sd
|
88 |
+
|
89 |
+
def load_clipvision_from_sd(sd, prefix="", convert_keys=False):
|
90 |
+
if convert_keys:
|
91 |
+
sd = convert_to_transformers(sd, prefix)
|
92 |
+
if "vision_model.encoder.layers.47.layer_norm1.weight" in sd:
|
93 |
+
json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_g.json")
|
94 |
+
elif "vision_model.encoder.layers.30.layer_norm1.weight" in sd:
|
95 |
+
json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_h.json")
|
96 |
+
elif "vision_model.encoder.layers.22.layer_norm1.weight" in sd:
|
97 |
+
if sd["vision_model.embeddings.position_embedding.weight"].shape[0] == 577:
|
98 |
+
json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_vitl_336.json")
|
99 |
+
else:
|
100 |
+
json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_vitl.json")
|
101 |
+
else:
|
102 |
+
return None
|
103 |
+
|
104 |
+
clip = ClipVisionModel(json_config)
|
105 |
+
m, u = clip.load_sd(sd)
|
106 |
+
if len(m) > 0:
|
107 |
+
logging.warning("missing clip vision: {}".format(m))
|
108 |
+
u = set(u)
|
109 |
+
keys = list(sd.keys())
|
110 |
+
for k in keys:
|
111 |
+
if k not in u:
|
112 |
+
t = sd.pop(k)
|
113 |
+
del t
|
114 |
+
return clip
|
115 |
+
|
116 |
+
def load(ckpt_path):
|
117 |
+
sd = load_torch_file(ckpt_path)
|
118 |
+
if "visual.transformer.resblocks.0.attn.in_proj_weight" in sd:
|
119 |
+
return load_clipvision_from_sd(sd, prefix="visual.", convert_keys=True)
|
120 |
+
else:
|
121 |
+
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/conds.py
ADDED
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import math
|
3 |
+
import comfy.utils
|
4 |
+
|
5 |
+
|
6 |
+
def lcm(a, b): #TODO: eventually replace by math.lcm (added in python3.9)
|
7 |
+
return abs(a*b) // math.gcd(a, b)
|
8 |
+
|
9 |
+
class CONDRegular:
|
10 |
+
def __init__(self, cond):
|
11 |
+
self.cond = cond
|
12 |
+
|
13 |
+
def _copy_with(self, cond):
|
14 |
+
return self.__class__(cond)
|
15 |
+
|
16 |
+
def process_cond(self, batch_size, device, **kwargs):
|
17 |
+
return self._copy_with(comfy.utils.repeat_to_batch_size(self.cond, batch_size).to(device))
|
18 |
+
|
19 |
+
def can_concat(self, other):
|
20 |
+
if self.cond.shape != other.cond.shape:
|
21 |
+
return False
|
22 |
+
return True
|
23 |
+
|
24 |
+
def concat(self, others):
|
25 |
+
conds = [self.cond]
|
26 |
+
for x in others:
|
27 |
+
conds.append(x.cond)
|
28 |
+
return torch.cat(conds)
|
29 |
+
|
30 |
+
class CONDNoiseShape(CONDRegular):
|
31 |
+
def process_cond(self, batch_size, device, area, **kwargs):
|
32 |
+
data = self.cond
|
33 |
+
if area is not None:
|
34 |
+
dims = len(area) // 2
|
35 |
+
for i in range(dims):
|
36 |
+
data = data.narrow(i + 2, area[i + dims], area[i])
|
37 |
+
|
38 |
+
return self._copy_with(comfy.utils.repeat_to_batch_size(data, batch_size).to(device))
|
39 |
+
|
40 |
+
|
41 |
+
class CONDCrossAttn(CONDRegular):
|
42 |
+
def can_concat(self, other):
|
43 |
+
s1 = self.cond.shape
|
44 |
+
s2 = other.cond.shape
|
45 |
+
if s1 != s2:
|
46 |
+
if s1[0] != s2[0] or s1[2] != s2[2]: #these 2 cases should not happen
|
47 |
+
return False
|
48 |
+
|
49 |
+
mult_min = lcm(s1[1], s2[1])
|
50 |
+
diff = mult_min // min(s1[1], s2[1])
|
51 |
+
if diff > 4: #arbitrary limit on the padding because it's probably going to impact performance negatively if it's too much
|
52 |
+
return False
|
53 |
+
return True
|
54 |
+
|
55 |
+
def concat(self, others):
|
56 |
+
conds = [self.cond]
|
57 |
+
crossattn_max_len = self.cond.shape[1]
|
58 |
+
for x in others:
|
59 |
+
c = x.cond
|
60 |
+
crossattn_max_len = lcm(crossattn_max_len, c.shape[1])
|
61 |
+
conds.append(c)
|
62 |
+
|
63 |
+
out = []
|
64 |
+
for c in conds:
|
65 |
+
if c.shape[1] < crossattn_max_len:
|
66 |
+
c = c.repeat(1, crossattn_max_len // c.shape[1], 1) #padding with repeat doesn't change result
|
67 |
+
out.append(c)
|
68 |
+
return torch.cat(out)
|
69 |
+
|
70 |
+
class CONDConstant(CONDRegular):
|
71 |
+
def __init__(self, cond):
|
72 |
+
self.cond = cond
|
73 |
+
|
74 |
+
def process_cond(self, batch_size, device, **kwargs):
|
75 |
+
return self._copy_with(self.cond)
|
76 |
+
|
77 |
+
def can_concat(self, other):
|
78 |
+
if self.cond != other.cond:
|
79 |
+
return False
|
80 |
+
return True
|
81 |
+
|
82 |
+
def concat(self, others):
|
83 |
+
return self.cond
|
comfy/controlnet.py
ADDED
@@ -0,0 +1,610 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import math
|
3 |
+
import os
|
4 |
+
import logging
|
5 |
+
import comfy.utils
|
6 |
+
import comfy.model_management
|
7 |
+
import comfy.model_detection
|
8 |
+
import comfy.model_patcher
|
9 |
+
import comfy.ops
|
10 |
+
import comfy.latent_formats
|
11 |
+
|
12 |
+
import comfy.cldm.cldm
|
13 |
+
import comfy.t2i_adapter.adapter
|
14 |
+
import comfy.ldm.cascade.controlnet
|
15 |
+
import comfy.cldm.mmdit
|
16 |
+
|
17 |
+
|
18 |
+
def broadcast_image_to(tensor, target_batch_size, batched_number):
|
19 |
+
current_batch_size = tensor.shape[0]
|
20 |
+
#print(current_batch_size, target_batch_size)
|
21 |
+
if current_batch_size == 1:
|
22 |
+
return tensor
|
23 |
+
|
24 |
+
per_batch = target_batch_size // batched_number
|
25 |
+
tensor = tensor[:per_batch]
|
26 |
+
|
27 |
+
if per_batch > tensor.shape[0]:
|
28 |
+
tensor = torch.cat([tensor] * (per_batch // tensor.shape[0]) + [tensor[:(per_batch % tensor.shape[0])]], dim=0)
|
29 |
+
|
30 |
+
current_batch_size = tensor.shape[0]
|
31 |
+
if current_batch_size == target_batch_size:
|
32 |
+
return tensor
|
33 |
+
else:
|
34 |
+
return torch.cat([tensor] * batched_number, dim=0)
|
35 |
+
|
36 |
+
class ControlBase:
|
37 |
+
def __init__(self, device=None):
|
38 |
+
self.cond_hint_original = None
|
39 |
+
self.cond_hint = None
|
40 |
+
self.strength = 1.0
|
41 |
+
self.timestep_percent_range = (0.0, 1.0)
|
42 |
+
self.latent_format = None
|
43 |
+
self.vae = None
|
44 |
+
self.global_average_pooling = False
|
45 |
+
self.timestep_range = None
|
46 |
+
self.compression_ratio = 8
|
47 |
+
self.upscale_algorithm = 'nearest-exact'
|
48 |
+
self.extra_args = {}
|
49 |
+
|
50 |
+
if device is None:
|
51 |
+
device = comfy.model_management.get_torch_device()
|
52 |
+
self.device = device
|
53 |
+
self.previous_controlnet = None
|
54 |
+
|
55 |
+
def set_cond_hint(self, cond_hint, strength=1.0, timestep_percent_range=(0.0, 1.0), vae=None):
|
56 |
+
self.cond_hint_original = cond_hint
|
57 |
+
self.strength = strength
|
58 |
+
self.timestep_percent_range = timestep_percent_range
|
59 |
+
if self.latent_format is not None:
|
60 |
+
self.vae = vae
|
61 |
+
return self
|
62 |
+
|
63 |
+
def pre_run(self, model, percent_to_timestep_function):
|
64 |
+
self.timestep_range = (percent_to_timestep_function(self.timestep_percent_range[0]), percent_to_timestep_function(self.timestep_percent_range[1]))
|
65 |
+
if self.previous_controlnet is not None:
|
66 |
+
self.previous_controlnet.pre_run(model, percent_to_timestep_function)
|
67 |
+
|
68 |
+
def set_previous_controlnet(self, controlnet):
|
69 |
+
self.previous_controlnet = controlnet
|
70 |
+
return self
|
71 |
+
|
72 |
+
def cleanup(self):
|
73 |
+
if self.previous_controlnet is not None:
|
74 |
+
self.previous_controlnet.cleanup()
|
75 |
+
if self.cond_hint is not None:
|
76 |
+
del self.cond_hint
|
77 |
+
self.cond_hint = None
|
78 |
+
self.timestep_range = None
|
79 |
+
|
80 |
+
def get_models(self):
|
81 |
+
out = []
|
82 |
+
if self.previous_controlnet is not None:
|
83 |
+
out += self.previous_controlnet.get_models()
|
84 |
+
return out
|
85 |
+
|
86 |
+
def copy_to(self, c):
|
87 |
+
c.cond_hint_original = self.cond_hint_original
|
88 |
+
c.strength = self.strength
|
89 |
+
c.timestep_percent_range = self.timestep_percent_range
|
90 |
+
c.global_average_pooling = self.global_average_pooling
|
91 |
+
c.compression_ratio = self.compression_ratio
|
92 |
+
c.upscale_algorithm = self.upscale_algorithm
|
93 |
+
c.latent_format = self.latent_format
|
94 |
+
c.extra_args = self.extra_args.copy()
|
95 |
+
c.vae = self.vae
|
96 |
+
|
97 |
+
def inference_memory_requirements(self, dtype):
|
98 |
+
if self.previous_controlnet is not None:
|
99 |
+
return self.previous_controlnet.inference_memory_requirements(dtype)
|
100 |
+
return 0
|
101 |
+
|
102 |
+
def control_merge(self, control, control_prev, output_dtype):
|
103 |
+
out = {'input':[], 'middle':[], 'output': []}
|
104 |
+
|
105 |
+
for key in control:
|
106 |
+
control_output = control[key]
|
107 |
+
applied_to = set()
|
108 |
+
for i in range(len(control_output)):
|
109 |
+
x = control_output[i]
|
110 |
+
if x is not None:
|
111 |
+
if self.global_average_pooling:
|
112 |
+
x = torch.mean(x, dim=(2, 3), keepdim=True).repeat(1, 1, x.shape[2], x.shape[3])
|
113 |
+
|
114 |
+
if x not in applied_to: #memory saving strategy, allow shared tensors and only apply strength to shared tensors once
|
115 |
+
applied_to.add(x)
|
116 |
+
x *= self.strength
|
117 |
+
|
118 |
+
if x.dtype != output_dtype:
|
119 |
+
x = x.to(output_dtype)
|
120 |
+
|
121 |
+
out[key].append(x)
|
122 |
+
|
123 |
+
if control_prev is not None:
|
124 |
+
for x in ['input', 'middle', 'output']:
|
125 |
+
o = out[x]
|
126 |
+
for i in range(len(control_prev[x])):
|
127 |
+
prev_val = control_prev[x][i]
|
128 |
+
if i >= len(o):
|
129 |
+
o.append(prev_val)
|
130 |
+
elif prev_val is not None:
|
131 |
+
if o[i] is None:
|
132 |
+
o[i] = prev_val
|
133 |
+
else:
|
134 |
+
if o[i].shape[0] < prev_val.shape[0]:
|
135 |
+
o[i] = prev_val + o[i]
|
136 |
+
else:
|
137 |
+
o[i] = prev_val + o[i] #TODO: change back to inplace add if shared tensors stop being an issue
|
138 |
+
return out
|
139 |
+
|
140 |
+
def set_extra_arg(self, argument, value=None):
|
141 |
+
self.extra_args[argument] = value
|
142 |
+
|
143 |
+
|
144 |
+
class ControlNet(ControlBase):
|
145 |
+
def __init__(self, control_model=None, global_average_pooling=False, compression_ratio=8, latent_format=None, device=None, load_device=None, manual_cast_dtype=None):
|
146 |
+
super().__init__(device)
|
147 |
+
self.control_model = control_model
|
148 |
+
self.load_device = load_device
|
149 |
+
if control_model is not None:
|
150 |
+
self.control_model_wrapped = comfy.model_patcher.ModelPatcher(self.control_model, load_device=load_device, offload_device=comfy.model_management.unet_offload_device())
|
151 |
+
|
152 |
+
self.compression_ratio = compression_ratio
|
153 |
+
self.global_average_pooling = global_average_pooling
|
154 |
+
self.model_sampling_current = None
|
155 |
+
self.manual_cast_dtype = manual_cast_dtype
|
156 |
+
self.latent_format = latent_format
|
157 |
+
|
158 |
+
def get_control(self, x_noisy, t, cond, batched_number):
|
159 |
+
control_prev = None
|
160 |
+
if self.previous_controlnet is not None:
|
161 |
+
control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number)
|
162 |
+
|
163 |
+
if self.timestep_range is not None:
|
164 |
+
if t[0] > self.timestep_range[0] or t[0] < self.timestep_range[1]:
|
165 |
+
if control_prev is not None:
|
166 |
+
return control_prev
|
167 |
+
else:
|
168 |
+
return None
|
169 |
+
|
170 |
+
dtype = self.control_model.dtype
|
171 |
+
if self.manual_cast_dtype is not None:
|
172 |
+
dtype = self.manual_cast_dtype
|
173 |
+
|
174 |
+
output_dtype = x_noisy.dtype
|
175 |
+
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]:
|
176 |
+
if self.cond_hint is not None:
|
177 |
+
del self.cond_hint
|
178 |
+
self.cond_hint = None
|
179 |
+
compression_ratio = self.compression_ratio
|
180 |
+
if self.vae is not None:
|
181 |
+
compression_ratio *= self.vae.downscale_ratio
|
182 |
+
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")
|
183 |
+
if self.vae is not None:
|
184 |
+
loaded_models = comfy.model_management.loaded_models(only_currently_used=True)
|
185 |
+
self.cond_hint = self.vae.encode(self.cond_hint.movedim(1, -1))
|
186 |
+
comfy.model_management.load_models_gpu(loaded_models)
|
187 |
+
if self.latent_format is not None:
|
188 |
+
self.cond_hint = self.latent_format.process_in(self.cond_hint)
|
189 |
+
self.cond_hint = self.cond_hint.to(device=self.device, dtype=dtype)
|
190 |
+
if x_noisy.shape[0] != self.cond_hint.shape[0]:
|
191 |
+
self.cond_hint = broadcast_image_to(self.cond_hint, x_noisy.shape[0], batched_number)
|
192 |
+
|
193 |
+
context = cond.get('crossattn_controlnet', cond['c_crossattn'])
|
194 |
+
y = cond.get('y', None)
|
195 |
+
if y is not None:
|
196 |
+
y = y.to(dtype)
|
197 |
+
timestep = self.model_sampling_current.timestep(t)
|
198 |
+
x_noisy = self.model_sampling_current.calculate_input(t, x_noisy)
|
199 |
+
|
200 |
+
control = self.control_model(x=x_noisy.to(dtype), hint=self.cond_hint, timesteps=timestep.float(), context=context.to(dtype), y=y, **self.extra_args)
|
201 |
+
return self.control_merge(control, control_prev, output_dtype)
|
202 |
+
|
203 |
+
def copy(self):
|
204 |
+
c = ControlNet(None, global_average_pooling=self.global_average_pooling, load_device=self.load_device, manual_cast_dtype=self.manual_cast_dtype)
|
205 |
+
c.control_model = self.control_model
|
206 |
+
c.control_model_wrapped = self.control_model_wrapped
|
207 |
+
self.copy_to(c)
|
208 |
+
return c
|
209 |
+
|
210 |
+
def get_models(self):
|
211 |
+
out = super().get_models()
|
212 |
+
out.append(self.control_model_wrapped)
|
213 |
+
return out
|
214 |
+
|
215 |
+
def pre_run(self, model, percent_to_timestep_function):
|
216 |
+
super().pre_run(model, percent_to_timestep_function)
|
217 |
+
self.model_sampling_current = model.model_sampling
|
218 |
+
|
219 |
+
def cleanup(self):
|
220 |
+
self.model_sampling_current = None
|
221 |
+
super().cleanup()
|
222 |
+
|
223 |
+
class ControlLoraOps:
|
224 |
+
class Linear(torch.nn.Module, comfy.ops.CastWeightBiasOp):
|
225 |
+
def __init__(self, in_features: int, out_features: int, bias: bool = True,
|
226 |
+
device=None, dtype=None) -> None:
|
227 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
228 |
+
super().__init__()
|
229 |
+
self.in_features = in_features
|
230 |
+
self.out_features = out_features
|
231 |
+
self.weight = None
|
232 |
+
self.up = None
|
233 |
+
self.down = None
|
234 |
+
self.bias = None
|
235 |
+
|
236 |
+
def forward(self, input):
|
237 |
+
weight, bias = comfy.ops.cast_bias_weight(self, input)
|
238 |
+
if self.up is not None:
|
239 |
+
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)
|
240 |
+
else:
|
241 |
+
return torch.nn.functional.linear(input, weight, bias)
|
242 |
+
|
243 |
+
class Conv2d(torch.nn.Module, comfy.ops.CastWeightBiasOp):
|
244 |
+
def __init__(
|
245 |
+
self,
|
246 |
+
in_channels,
|
247 |
+
out_channels,
|
248 |
+
kernel_size,
|
249 |
+
stride=1,
|
250 |
+
padding=0,
|
251 |
+
dilation=1,
|
252 |
+
groups=1,
|
253 |
+
bias=True,
|
254 |
+
padding_mode='zeros',
|
255 |
+
device=None,
|
256 |
+
dtype=None
|
257 |
+
):
|
258 |
+
super().__init__()
|
259 |
+
self.in_channels = in_channels
|
260 |
+
self.out_channels = out_channels
|
261 |
+
self.kernel_size = kernel_size
|
262 |
+
self.stride = stride
|
263 |
+
self.padding = padding
|
264 |
+
self.dilation = dilation
|
265 |
+
self.transposed = False
|
266 |
+
self.output_padding = 0
|
267 |
+
self.groups = groups
|
268 |
+
self.padding_mode = padding_mode
|
269 |
+
|
270 |
+
self.weight = None
|
271 |
+
self.bias = None
|
272 |
+
self.up = None
|
273 |
+
self.down = None
|
274 |
+
|
275 |
+
|
276 |
+
def forward(self, input):
|
277 |
+
weight, bias = comfy.ops.cast_bias_weight(self, input)
|
278 |
+
if self.up is not None:
|
279 |
+
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)
|
280 |
+
else:
|
281 |
+
return torch.nn.functional.conv2d(input, weight, bias, self.stride, self.padding, self.dilation, self.groups)
|
282 |
+
|
283 |
+
|
284 |
+
class ControlLora(ControlNet):
|
285 |
+
def __init__(self, control_weights, global_average_pooling=False, device=None):
|
286 |
+
ControlBase.__init__(self, device)
|
287 |
+
self.control_weights = control_weights
|
288 |
+
self.global_average_pooling = global_average_pooling
|
289 |
+
|
290 |
+
def pre_run(self, model, percent_to_timestep_function):
|
291 |
+
super().pre_run(model, percent_to_timestep_function)
|
292 |
+
controlnet_config = model.model_config.unet_config.copy()
|
293 |
+
controlnet_config.pop("out_channels")
|
294 |
+
controlnet_config["hint_channels"] = self.control_weights["input_hint_block.0.weight"].shape[1]
|
295 |
+
self.manual_cast_dtype = model.manual_cast_dtype
|
296 |
+
dtype = model.get_dtype()
|
297 |
+
if self.manual_cast_dtype is None:
|
298 |
+
class control_lora_ops(ControlLoraOps, comfy.ops.disable_weight_init):
|
299 |
+
pass
|
300 |
+
else:
|
301 |
+
class control_lora_ops(ControlLoraOps, comfy.ops.manual_cast):
|
302 |
+
pass
|
303 |
+
dtype = self.manual_cast_dtype
|
304 |
+
|
305 |
+
controlnet_config["operations"] = control_lora_ops
|
306 |
+
controlnet_config["dtype"] = dtype
|
307 |
+
self.control_model = comfy.cldm.cldm.ControlNet(**controlnet_config)
|
308 |
+
self.control_model.to(comfy.model_management.get_torch_device())
|
309 |
+
diffusion_model = model.diffusion_model
|
310 |
+
sd = diffusion_model.state_dict()
|
311 |
+
cm = self.control_model.state_dict()
|
312 |
+
|
313 |
+
for k in sd:
|
314 |
+
weight = sd[k]
|
315 |
+
try:
|
316 |
+
comfy.utils.set_attr_param(self.control_model, k, weight)
|
317 |
+
except:
|
318 |
+
pass
|
319 |
+
|
320 |
+
for k in self.control_weights:
|
321 |
+
if k not in {"lora_controlnet"}:
|
322 |
+
comfy.utils.set_attr_param(self.control_model, k, self.control_weights[k].to(dtype).to(comfy.model_management.get_torch_device()))
|
323 |
+
|
324 |
+
def copy(self):
|
325 |
+
c = ControlLora(self.control_weights, global_average_pooling=self.global_average_pooling)
|
326 |
+
self.copy_to(c)
|
327 |
+
return c
|
328 |
+
|
329 |
+
def cleanup(self):
|
330 |
+
del self.control_model
|
331 |
+
self.control_model = None
|
332 |
+
super().cleanup()
|
333 |
+
|
334 |
+
def get_models(self):
|
335 |
+
out = ControlBase.get_models(self)
|
336 |
+
return out
|
337 |
+
|
338 |
+
def inference_memory_requirements(self, dtype):
|
339 |
+
return comfy.utils.calculate_parameters(self.control_weights) * comfy.model_management.dtype_size(dtype) + ControlBase.inference_memory_requirements(self, dtype)
|
340 |
+
|
341 |
+
def load_controlnet_mmdit(sd):
|
342 |
+
new_sd = comfy.model_detection.convert_diffusers_mmdit(sd, "")
|
343 |
+
model_config = comfy.model_detection.model_config_from_unet(new_sd, "", True)
|
344 |
+
num_blocks = comfy.model_detection.count_blocks(new_sd, 'joint_blocks.{}.')
|
345 |
+
for k in sd:
|
346 |
+
new_sd[k] = sd[k]
|
347 |
+
|
348 |
+
supported_inference_dtypes = model_config.supported_inference_dtypes
|
349 |
+
|
350 |
+
controlnet_config = model_config.unet_config
|
351 |
+
unet_dtype = comfy.model_management.unet_dtype(supported_dtypes=supported_inference_dtypes)
|
352 |
+
load_device = comfy.model_management.get_torch_device()
|
353 |
+
manual_cast_dtype = comfy.model_management.unet_manual_cast(unet_dtype, load_device)
|
354 |
+
if manual_cast_dtype is not None:
|
355 |
+
operations = comfy.ops.manual_cast
|
356 |
+
else:
|
357 |
+
operations = comfy.ops.disable_weight_init
|
358 |
+
|
359 |
+
control_model = comfy.cldm.mmdit.ControlNet(num_blocks=num_blocks, operations=operations, device=load_device, dtype=unet_dtype, **controlnet_config)
|
360 |
+
missing, unexpected = control_model.load_state_dict(new_sd, strict=False)
|
361 |
+
|
362 |
+
if len(missing) > 0:
|
363 |
+
logging.warning("missing controlnet keys: {}".format(missing))
|
364 |
+
|
365 |
+
if len(unexpected) > 0:
|
366 |
+
logging.debug("unexpected controlnet keys: {}".format(unexpected))
|
367 |
+
|
368 |
+
latent_format = comfy.latent_formats.SD3()
|
369 |
+
latent_format.shift_factor = 0 #SD3 controlnet weirdness
|
370 |
+
control = ControlNet(control_model, compression_ratio=1, latent_format=latent_format, load_device=load_device, manual_cast_dtype=manual_cast_dtype)
|
371 |
+
return control
|
372 |
+
|
373 |
+
|
374 |
+
def load_controlnet(ckpt_path, model=None):
|
375 |
+
controlnet_data = comfy.utils.load_torch_file(ckpt_path, safe_load=True)
|
376 |
+
if "lora_controlnet" in controlnet_data:
|
377 |
+
return ControlLora(controlnet_data)
|
378 |
+
|
379 |
+
controlnet_config = None
|
380 |
+
supported_inference_dtypes = None
|
381 |
+
|
382 |
+
if "controlnet_cond_embedding.conv_in.weight" in controlnet_data: #diffusers format
|
383 |
+
controlnet_config = comfy.model_detection.unet_config_from_diffusers_unet(controlnet_data)
|
384 |
+
diffusers_keys = comfy.utils.unet_to_diffusers(controlnet_config)
|
385 |
+
diffusers_keys["controlnet_mid_block.weight"] = "middle_block_out.0.weight"
|
386 |
+
diffusers_keys["controlnet_mid_block.bias"] = "middle_block_out.0.bias"
|
387 |
+
|
388 |
+
count = 0
|
389 |
+
loop = True
|
390 |
+
while loop:
|
391 |
+
suffix = [".weight", ".bias"]
|
392 |
+
for s in suffix:
|
393 |
+
k_in = "controlnet_down_blocks.{}{}".format(count, s)
|
394 |
+
k_out = "zero_convs.{}.0{}".format(count, s)
|
395 |
+
if k_in not in controlnet_data:
|
396 |
+
loop = False
|
397 |
+
break
|
398 |
+
diffusers_keys[k_in] = k_out
|
399 |
+
count += 1
|
400 |
+
|
401 |
+
count = 0
|
402 |
+
loop = True
|
403 |
+
while loop:
|
404 |
+
suffix = [".weight", ".bias"]
|
405 |
+
for s in suffix:
|
406 |
+
if count == 0:
|
407 |
+
k_in = "controlnet_cond_embedding.conv_in{}".format(s)
|
408 |
+
else:
|
409 |
+
k_in = "controlnet_cond_embedding.blocks.{}{}".format(count - 1, s)
|
410 |
+
k_out = "input_hint_block.{}{}".format(count * 2, s)
|
411 |
+
if k_in not in controlnet_data:
|
412 |
+
k_in = "controlnet_cond_embedding.conv_out{}".format(s)
|
413 |
+
loop = False
|
414 |
+
diffusers_keys[k_in] = k_out
|
415 |
+
count += 1
|
416 |
+
|
417 |
+
new_sd = {}
|
418 |
+
for k in diffusers_keys:
|
419 |
+
if k in controlnet_data:
|
420 |
+
new_sd[diffusers_keys[k]] = controlnet_data.pop(k)
|
421 |
+
|
422 |
+
if "control_add_embedding.linear_1.bias" in controlnet_data: #Union Controlnet
|
423 |
+
controlnet_config["union_controlnet_num_control_type"] = controlnet_data["task_embedding"].shape[0]
|
424 |
+
for k in list(controlnet_data.keys()):
|
425 |
+
new_k = k.replace('.attn.in_proj_', '.attn.in_proj.')
|
426 |
+
new_sd[new_k] = controlnet_data.pop(k)
|
427 |
+
|
428 |
+
leftover_keys = controlnet_data.keys()
|
429 |
+
if len(leftover_keys) > 0:
|
430 |
+
logging.warning("leftover keys: {}".format(leftover_keys))
|
431 |
+
controlnet_data = new_sd
|
432 |
+
elif "controlnet_blocks.0.weight" in controlnet_data: #SD3 diffusers format
|
433 |
+
return load_controlnet_mmdit(controlnet_data)
|
434 |
+
|
435 |
+
pth_key = 'control_model.zero_convs.0.0.weight'
|
436 |
+
pth = False
|
437 |
+
key = 'zero_convs.0.0.weight'
|
438 |
+
if pth_key in controlnet_data:
|
439 |
+
pth = True
|
440 |
+
key = pth_key
|
441 |
+
prefix = "control_model."
|
442 |
+
elif key in controlnet_data:
|
443 |
+
prefix = ""
|
444 |
+
else:
|
445 |
+
net = load_t2i_adapter(controlnet_data)
|
446 |
+
if net is None:
|
447 |
+
logging.error("error checkpoint does not contain controlnet or t2i adapter data {}".format(ckpt_path))
|
448 |
+
return net
|
449 |
+
|
450 |
+
if controlnet_config is None:
|
451 |
+
model_config = comfy.model_detection.model_config_from_unet(controlnet_data, prefix, True)
|
452 |
+
supported_inference_dtypes = model_config.supported_inference_dtypes
|
453 |
+
controlnet_config = model_config.unet_config
|
454 |
+
|
455 |
+
load_device = comfy.model_management.get_torch_device()
|
456 |
+
if supported_inference_dtypes is None:
|
457 |
+
unet_dtype = comfy.model_management.unet_dtype()
|
458 |
+
else:
|
459 |
+
unet_dtype = comfy.model_management.unet_dtype(supported_dtypes=supported_inference_dtypes)
|
460 |
+
|
461 |
+
manual_cast_dtype = comfy.model_management.unet_manual_cast(unet_dtype, load_device)
|
462 |
+
if manual_cast_dtype is not None:
|
463 |
+
controlnet_config["operations"] = comfy.ops.manual_cast
|
464 |
+
controlnet_config["dtype"] = unet_dtype
|
465 |
+
controlnet_config.pop("out_channels")
|
466 |
+
controlnet_config["hint_channels"] = controlnet_data["{}input_hint_block.0.weight".format(prefix)].shape[1]
|
467 |
+
control_model = comfy.cldm.cldm.ControlNet(**controlnet_config)
|
468 |
+
|
469 |
+
if pth:
|
470 |
+
if 'difference' in controlnet_data:
|
471 |
+
if model is not None:
|
472 |
+
comfy.model_management.load_models_gpu([model])
|
473 |
+
model_sd = model.model_state_dict()
|
474 |
+
for x in controlnet_data:
|
475 |
+
c_m = "control_model."
|
476 |
+
if x.startswith(c_m):
|
477 |
+
sd_key = "diffusion_model.{}".format(x[len(c_m):])
|
478 |
+
if sd_key in model_sd:
|
479 |
+
cd = controlnet_data[x]
|
480 |
+
cd += model_sd[sd_key].type(cd.dtype).to(cd.device)
|
481 |
+
else:
|
482 |
+
logging.warning("WARNING: Loaded a diff controlnet without a model. It will very likely not work.")
|
483 |
+
|
484 |
+
class WeightsLoader(torch.nn.Module):
|
485 |
+
pass
|
486 |
+
w = WeightsLoader()
|
487 |
+
w.control_model = control_model
|
488 |
+
missing, unexpected = w.load_state_dict(controlnet_data, strict=False)
|
489 |
+
else:
|
490 |
+
missing, unexpected = control_model.load_state_dict(controlnet_data, strict=False)
|
491 |
+
|
492 |
+
if len(missing) > 0:
|
493 |
+
logging.warning("missing controlnet keys: {}".format(missing))
|
494 |
+
|
495 |
+
if len(unexpected) > 0:
|
496 |
+
logging.debug("unexpected controlnet keys: {}".format(unexpected))
|
497 |
+
|
498 |
+
global_average_pooling = False
|
499 |
+
filename = os.path.splitext(ckpt_path)[0]
|
500 |
+
if filename.endswith("_shuffle") or filename.endswith("_shuffle_fp16"): #TODO: smarter way of enabling global_average_pooling
|
501 |
+
global_average_pooling = True
|
502 |
+
|
503 |
+
control = ControlNet(control_model, global_average_pooling=global_average_pooling, load_device=load_device, manual_cast_dtype=manual_cast_dtype)
|
504 |
+
return control
|
505 |
+
|
506 |
+
class T2IAdapter(ControlBase):
|
507 |
+
def __init__(self, t2i_model, channels_in, compression_ratio, upscale_algorithm, device=None):
|
508 |
+
super().__init__(device)
|
509 |
+
self.t2i_model = t2i_model
|
510 |
+
self.channels_in = channels_in
|
511 |
+
self.control_input = None
|
512 |
+
self.compression_ratio = compression_ratio
|
513 |
+
self.upscale_algorithm = upscale_algorithm
|
514 |
+
|
515 |
+
def scale_image_to(self, width, height):
|
516 |
+
unshuffle_amount = self.t2i_model.unshuffle_amount
|
517 |
+
width = math.ceil(width / unshuffle_amount) * unshuffle_amount
|
518 |
+
height = math.ceil(height / unshuffle_amount) * unshuffle_amount
|
519 |
+
return width, height
|
520 |
+
|
521 |
+
def get_control(self, x_noisy, t, cond, batched_number):
|
522 |
+
control_prev = None
|
523 |
+
if self.previous_controlnet is not None:
|
524 |
+
control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number)
|
525 |
+
|
526 |
+
if self.timestep_range is not None:
|
527 |
+
if t[0] > self.timestep_range[0] or t[0] < self.timestep_range[1]:
|
528 |
+
if control_prev is not None:
|
529 |
+
return control_prev
|
530 |
+
else:
|
531 |
+
return None
|
532 |
+
|
533 |
+
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]:
|
534 |
+
if self.cond_hint is not None:
|
535 |
+
del self.cond_hint
|
536 |
+
self.control_input = None
|
537 |
+
self.cond_hint = None
|
538 |
+
width, height = self.scale_image_to(x_noisy.shape[3] * self.compression_ratio, x_noisy.shape[2] * self.compression_ratio)
|
539 |
+
self.cond_hint = comfy.utils.common_upscale(self.cond_hint_original, width, height, self.upscale_algorithm, "center").float().to(self.device)
|
540 |
+
if self.channels_in == 1 and self.cond_hint.shape[1] > 1:
|
541 |
+
self.cond_hint = torch.mean(self.cond_hint, 1, keepdim=True)
|
542 |
+
if x_noisy.shape[0] != self.cond_hint.shape[0]:
|
543 |
+
self.cond_hint = broadcast_image_to(self.cond_hint, x_noisy.shape[0], batched_number)
|
544 |
+
if self.control_input is None:
|
545 |
+
self.t2i_model.to(x_noisy.dtype)
|
546 |
+
self.t2i_model.to(self.device)
|
547 |
+
self.control_input = self.t2i_model(self.cond_hint.to(x_noisy.dtype))
|
548 |
+
self.t2i_model.cpu()
|
549 |
+
|
550 |
+
control_input = {}
|
551 |
+
for k in self.control_input:
|
552 |
+
control_input[k] = list(map(lambda a: None if a is None else a.clone(), self.control_input[k]))
|
553 |
+
|
554 |
+
return self.control_merge(control_input, control_prev, x_noisy.dtype)
|
555 |
+
|
556 |
+
def copy(self):
|
557 |
+
c = T2IAdapter(self.t2i_model, self.channels_in, self.compression_ratio, self.upscale_algorithm)
|
558 |
+
self.copy_to(c)
|
559 |
+
return c
|
560 |
+
|
561 |
+
def load_t2i_adapter(t2i_data):
|
562 |
+
compression_ratio = 8
|
563 |
+
upscale_algorithm = 'nearest-exact'
|
564 |
+
|
565 |
+
if 'adapter' in t2i_data:
|
566 |
+
t2i_data = t2i_data['adapter']
|
567 |
+
if 'adapter.body.0.resnets.0.block1.weight' in t2i_data: #diffusers format
|
568 |
+
prefix_replace = {}
|
569 |
+
for i in range(4):
|
570 |
+
for j in range(2):
|
571 |
+
prefix_replace["adapter.body.{}.resnets.{}.".format(i, j)] = "body.{}.".format(i * 2 + j)
|
572 |
+
prefix_replace["adapter.body.{}.".format(i, j)] = "body.{}.".format(i * 2)
|
573 |
+
prefix_replace["adapter."] = ""
|
574 |
+
t2i_data = comfy.utils.state_dict_prefix_replace(t2i_data, prefix_replace)
|
575 |
+
keys = t2i_data.keys()
|
576 |
+
|
577 |
+
if "body.0.in_conv.weight" in keys:
|
578 |
+
cin = t2i_data['body.0.in_conv.weight'].shape[1]
|
579 |
+
model_ad = comfy.t2i_adapter.adapter.Adapter_light(cin=cin, channels=[320, 640, 1280, 1280], nums_rb=4)
|
580 |
+
elif 'conv_in.weight' in keys:
|
581 |
+
cin = t2i_data['conv_in.weight'].shape[1]
|
582 |
+
channel = t2i_data['conv_in.weight'].shape[0]
|
583 |
+
ksize = t2i_data['body.0.block2.weight'].shape[2]
|
584 |
+
use_conv = False
|
585 |
+
down_opts = list(filter(lambda a: a.endswith("down_opt.op.weight"), keys))
|
586 |
+
if len(down_opts) > 0:
|
587 |
+
use_conv = True
|
588 |
+
xl = False
|
589 |
+
if cin == 256 or cin == 768:
|
590 |
+
xl = True
|
591 |
+
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)
|
592 |
+
elif "backbone.0.0.weight" in keys:
|
593 |
+
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])
|
594 |
+
compression_ratio = 32
|
595 |
+
upscale_algorithm = 'bilinear'
|
596 |
+
elif "backbone.10.blocks.0.weight" in keys:
|
597 |
+
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])
|
598 |
+
compression_ratio = 1
|
599 |
+
upscale_algorithm = 'nearest-exact'
|
600 |
+
else:
|
601 |
+
return None
|
602 |
+
|
603 |
+
missing, unexpected = model_ad.load_state_dict(t2i_data)
|
604 |
+
if len(missing) > 0:
|
605 |
+
logging.warning("t2i missing {}".format(missing))
|
606 |
+
|
607 |
+
if len(unexpected) > 0:
|
608 |
+
logging.debug("t2i unexpected {}".format(unexpected))
|
609 |
+
|
610 |
+
return T2IAdapter(model_ad, model_ad.input_channels, compression_ratio, upscale_algorithm)
|
comfy/diffusers_convert.py
ADDED
@@ -0,0 +1,281 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
# UNet Conversion #
|
9 |
+
# =================#
|
10 |
+
|
11 |
+
unet_conversion_map = [
|
12 |
+
# (stable-diffusion, HF Diffusers)
|
13 |
+
("time_embed.0.weight", "time_embedding.linear_1.weight"),
|
14 |
+
("time_embed.0.bias", "time_embedding.linear_1.bias"),
|
15 |
+
("time_embed.2.weight", "time_embedding.linear_2.weight"),
|
16 |
+
("time_embed.2.bias", "time_embedding.linear_2.bias"),
|
17 |
+
("input_blocks.0.0.weight", "conv_in.weight"),
|
18 |
+
("input_blocks.0.0.bias", "conv_in.bias"),
|
19 |
+
("out.0.weight", "conv_norm_out.weight"),
|
20 |
+
("out.0.bias", "conv_norm_out.bias"),
|
21 |
+
("out.2.weight", "conv_out.weight"),
|
22 |
+
("out.2.bias", "conv_out.bias"),
|
23 |
+
]
|
24 |
+
|
25 |
+
unet_conversion_map_resnet = [
|
26 |
+
# (stable-diffusion, HF Diffusers)
|
27 |
+
("in_layers.0", "norm1"),
|
28 |
+
("in_layers.2", "conv1"),
|
29 |
+
("out_layers.0", "norm2"),
|
30 |
+
("out_layers.3", "conv2"),
|
31 |
+
("emb_layers.1", "time_emb_proj"),
|
32 |
+
("skip_connection", "conv_shortcut"),
|
33 |
+
]
|
34 |
+
|
35 |
+
unet_conversion_map_layer = []
|
36 |
+
# hardcoded number of downblocks and resnets/attentions...
|
37 |
+
# would need smarter logic for other networks.
|
38 |
+
for i in range(4):
|
39 |
+
# loop over downblocks/upblocks
|
40 |
+
|
41 |
+
for j in range(2):
|
42 |
+
# loop over resnets/attentions for downblocks
|
43 |
+
hf_down_res_prefix = f"down_blocks.{i}.resnets.{j}."
|
44 |
+
sd_down_res_prefix = f"input_blocks.{3 * i + j + 1}.0."
|
45 |
+
unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix))
|
46 |
+
|
47 |
+
if i < 3:
|
48 |
+
# no attention layers in down_blocks.3
|
49 |
+
hf_down_atn_prefix = f"down_blocks.{i}.attentions.{j}."
|
50 |
+
sd_down_atn_prefix = f"input_blocks.{3 * i + j + 1}.1."
|
51 |
+
unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix))
|
52 |
+
|
53 |
+
for j in range(3):
|
54 |
+
# loop over resnets/attentions for upblocks
|
55 |
+
hf_up_res_prefix = f"up_blocks.{i}.resnets.{j}."
|
56 |
+
sd_up_res_prefix = f"output_blocks.{3 * i + j}.0."
|
57 |
+
unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix))
|
58 |
+
|
59 |
+
if i > 0:
|
60 |
+
# no attention layers in up_blocks.0
|
61 |
+
hf_up_atn_prefix = f"up_blocks.{i}.attentions.{j}."
|
62 |
+
sd_up_atn_prefix = f"output_blocks.{3 * i + j}.1."
|
63 |
+
unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix))
|
64 |
+
|
65 |
+
if i < 3:
|
66 |
+
# no downsample in down_blocks.3
|
67 |
+
hf_downsample_prefix = f"down_blocks.{i}.downsamplers.0.conv."
|
68 |
+
sd_downsample_prefix = f"input_blocks.{3 * (i + 1)}.0.op."
|
69 |
+
unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix))
|
70 |
+
|
71 |
+
# no upsample in up_blocks.3
|
72 |
+
hf_upsample_prefix = f"up_blocks.{i}.upsamplers.0."
|
73 |
+
sd_upsample_prefix = f"output_blocks.{3 * i + 2}.{1 if i == 0 else 2}."
|
74 |
+
unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix))
|
75 |
+
|
76 |
+
hf_mid_atn_prefix = "mid_block.attentions.0."
|
77 |
+
sd_mid_atn_prefix = "middle_block.1."
|
78 |
+
unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix))
|
79 |
+
|
80 |
+
for j in range(2):
|
81 |
+
hf_mid_res_prefix = f"mid_block.resnets.{j}."
|
82 |
+
sd_mid_res_prefix = f"middle_block.{2 * j}."
|
83 |
+
unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix))
|
84 |
+
|
85 |
+
|
86 |
+
def convert_unet_state_dict(unet_state_dict):
|
87 |
+
# buyer beware: this is a *brittle* function,
|
88 |
+
# and correct output requires that all of these pieces interact in
|
89 |
+
# the exact order in which I have arranged them.
|
90 |
+
mapping = {k: k for k in unet_state_dict.keys()}
|
91 |
+
for sd_name, hf_name in unet_conversion_map:
|
92 |
+
mapping[hf_name] = sd_name
|
93 |
+
for k, v in mapping.items():
|
94 |
+
if "resnets" in k:
|
95 |
+
for sd_part, hf_part in unet_conversion_map_resnet:
|
96 |
+
v = v.replace(hf_part, sd_part)
|
97 |
+
mapping[k] = v
|
98 |
+
for k, v in mapping.items():
|
99 |
+
for sd_part, hf_part in unet_conversion_map_layer:
|
100 |
+
v = v.replace(hf_part, sd_part)
|
101 |
+
mapping[k] = v
|
102 |
+
new_state_dict = {v: unet_state_dict[k] for k, v in mapping.items()}
|
103 |
+
return new_state_dict
|
104 |
+
|
105 |
+
|
106 |
+
# ================#
|
107 |
+
# VAE Conversion #
|
108 |
+
# ================#
|
109 |
+
|
110 |
+
vae_conversion_map = [
|
111 |
+
# (stable-diffusion, HF Diffusers)
|
112 |
+
("nin_shortcut", "conv_shortcut"),
|
113 |
+
("norm_out", "conv_norm_out"),
|
114 |
+
("mid.attn_1.", "mid_block.attentions.0."),
|
115 |
+
]
|
116 |
+
|
117 |
+
for i in range(4):
|
118 |
+
# down_blocks have two resnets
|
119 |
+
for j in range(2):
|
120 |
+
hf_down_prefix = f"encoder.down_blocks.{i}.resnets.{j}."
|
121 |
+
sd_down_prefix = f"encoder.down.{i}.block.{j}."
|
122 |
+
vae_conversion_map.append((sd_down_prefix, hf_down_prefix))
|
123 |
+
|
124 |
+
if i < 3:
|
125 |
+
hf_downsample_prefix = f"down_blocks.{i}.downsamplers.0."
|
126 |
+
sd_downsample_prefix = f"down.{i}.downsample."
|
127 |
+
vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix))
|
128 |
+
|
129 |
+
hf_upsample_prefix = f"up_blocks.{i}.upsamplers.0."
|
130 |
+
sd_upsample_prefix = f"up.{3 - i}.upsample."
|
131 |
+
vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix))
|
132 |
+
|
133 |
+
# up_blocks have three resnets
|
134 |
+
# also, up blocks in hf are numbered in reverse from sd
|
135 |
+
for j in range(3):
|
136 |
+
hf_up_prefix = f"decoder.up_blocks.{i}.resnets.{j}."
|
137 |
+
sd_up_prefix = f"decoder.up.{3 - i}.block.{j}."
|
138 |
+
vae_conversion_map.append((sd_up_prefix, hf_up_prefix))
|
139 |
+
|
140 |
+
# this part accounts for mid blocks in both the encoder and the decoder
|
141 |
+
for i in range(2):
|
142 |
+
hf_mid_res_prefix = f"mid_block.resnets.{i}."
|
143 |
+
sd_mid_res_prefix = f"mid.block_{i + 1}."
|
144 |
+
vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix))
|
145 |
+
|
146 |
+
vae_conversion_map_attn = [
|
147 |
+
# (stable-diffusion, HF Diffusers)
|
148 |
+
("norm.", "group_norm."),
|
149 |
+
("q.", "query."),
|
150 |
+
("k.", "key."),
|
151 |
+
("v.", "value."),
|
152 |
+
("q.", "to_q."),
|
153 |
+
("k.", "to_k."),
|
154 |
+
("v.", "to_v."),
|
155 |
+
("proj_out.", "to_out.0."),
|
156 |
+
("proj_out.", "proj_attn."),
|
157 |
+
]
|
158 |
+
|
159 |
+
|
160 |
+
def reshape_weight_for_sd(w):
|
161 |
+
# convert HF linear weights to SD conv2d weights
|
162 |
+
return w.reshape(*w.shape, 1, 1)
|
163 |
+
|
164 |
+
|
165 |
+
def convert_vae_state_dict(vae_state_dict):
|
166 |
+
mapping = {k: k for k in vae_state_dict.keys()}
|
167 |
+
for k, v in mapping.items():
|
168 |
+
for sd_part, hf_part in vae_conversion_map:
|
169 |
+
v = v.replace(hf_part, sd_part)
|
170 |
+
mapping[k] = v
|
171 |
+
for k, v in mapping.items():
|
172 |
+
if "attentions" in k:
|
173 |
+
for sd_part, hf_part in vae_conversion_map_attn:
|
174 |
+
v = v.replace(hf_part, sd_part)
|
175 |
+
mapping[k] = v
|
176 |
+
new_state_dict = {v: vae_state_dict[k] for k, v in mapping.items()}
|
177 |
+
weights_to_convert = ["q", "k", "v", "proj_out"]
|
178 |
+
for k, v in new_state_dict.items():
|
179 |
+
for weight_name in weights_to_convert:
|
180 |
+
if f"mid.attn_1.{weight_name}.weight" in k:
|
181 |
+
logging.debug(f"Reshaping {k} for SD format")
|
182 |
+
new_state_dict[k] = reshape_weight_for_sd(v)
|
183 |
+
return new_state_dict
|
184 |
+
|
185 |
+
|
186 |
+
# =========================#
|
187 |
+
# Text Encoder Conversion #
|
188 |
+
# =========================#
|
189 |
+
|
190 |
+
|
191 |
+
textenc_conversion_lst = [
|
192 |
+
# (stable-diffusion, HF Diffusers)
|
193 |
+
("resblocks.", "text_model.encoder.layers."),
|
194 |
+
("ln_1", "layer_norm1"),
|
195 |
+
("ln_2", "layer_norm2"),
|
196 |
+
(".c_fc.", ".fc1."),
|
197 |
+
(".c_proj.", ".fc2."),
|
198 |
+
(".attn", ".self_attn"),
|
199 |
+
("ln_final.", "transformer.text_model.final_layer_norm."),
|
200 |
+
("token_embedding.weight", "transformer.text_model.embeddings.token_embedding.weight"),
|
201 |
+
("positional_embedding", "transformer.text_model.embeddings.position_embedding.weight"),
|
202 |
+
]
|
203 |
+
protected = {re.escape(x[1]): x[0] for x in textenc_conversion_lst}
|
204 |
+
textenc_pattern = re.compile("|".join(protected.keys()))
|
205 |
+
|
206 |
+
# Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp
|
207 |
+
code2idx = {"q": 0, "k": 1, "v": 2}
|
208 |
+
|
209 |
+
# This function exists because at the time of writing torch.cat can't do fp8 with cuda
|
210 |
+
def cat_tensors(tensors):
|
211 |
+
x = 0
|
212 |
+
for t in tensors:
|
213 |
+
x += t.shape[0]
|
214 |
+
|
215 |
+
shape = [x] + list(tensors[0].shape)[1:]
|
216 |
+
out = torch.empty(shape, device=tensors[0].device, dtype=tensors[0].dtype)
|
217 |
+
|
218 |
+
x = 0
|
219 |
+
for t in tensors:
|
220 |
+
out[x:x + t.shape[0]] = t
|
221 |
+
x += t.shape[0]
|
222 |
+
|
223 |
+
return out
|
224 |
+
|
225 |
+
def convert_text_enc_state_dict_v20(text_enc_dict, prefix=""):
|
226 |
+
new_state_dict = {}
|
227 |
+
capture_qkv_weight = {}
|
228 |
+
capture_qkv_bias = {}
|
229 |
+
for k, v in text_enc_dict.items():
|
230 |
+
if not k.startswith(prefix):
|
231 |
+
continue
|
232 |
+
if (
|
233 |
+
k.endswith(".self_attn.q_proj.weight")
|
234 |
+
or k.endswith(".self_attn.k_proj.weight")
|
235 |
+
or k.endswith(".self_attn.v_proj.weight")
|
236 |
+
):
|
237 |
+
k_pre = k[: -len(".q_proj.weight")]
|
238 |
+
k_code = k[-len("q_proj.weight")]
|
239 |
+
if k_pre not in capture_qkv_weight:
|
240 |
+
capture_qkv_weight[k_pre] = [None, None, None]
|
241 |
+
capture_qkv_weight[k_pre][code2idx[k_code]] = v
|
242 |
+
continue
|
243 |
+
|
244 |
+
if (
|
245 |
+
k.endswith(".self_attn.q_proj.bias")
|
246 |
+
or k.endswith(".self_attn.k_proj.bias")
|
247 |
+
or k.endswith(".self_attn.v_proj.bias")
|
248 |
+
):
|
249 |
+
k_pre = k[: -len(".q_proj.bias")]
|
250 |
+
k_code = k[-len("q_proj.bias")]
|
251 |
+
if k_pre not in capture_qkv_bias:
|
252 |
+
capture_qkv_bias[k_pre] = [None, None, None]
|
253 |
+
capture_qkv_bias[k_pre][code2idx[k_code]] = v
|
254 |
+
continue
|
255 |
+
|
256 |
+
text_proj = "transformer.text_projection.weight"
|
257 |
+
if k.endswith(text_proj):
|
258 |
+
new_state_dict[k.replace(text_proj, "text_projection")] = v.transpose(0, 1).contiguous()
|
259 |
+
else:
|
260 |
+
relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k)
|
261 |
+
new_state_dict[relabelled_key] = v
|
262 |
+
|
263 |
+
for k_pre, tensors in capture_qkv_weight.items():
|
264 |
+
if None in tensors:
|
265 |
+
raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing")
|
266 |
+
relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k_pre)
|
267 |
+
new_state_dict[relabelled_key + ".in_proj_weight"] = cat_tensors(tensors)
|
268 |
+
|
269 |
+
for k_pre, tensors in capture_qkv_bias.items():
|
270 |
+
if None in tensors:
|
271 |
+
raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing")
|
272 |
+
relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k_pre)
|
273 |
+
new_state_dict[relabelled_key + ".in_proj_bias"] = cat_tensors(tensors)
|
274 |
+
|
275 |
+
return new_state_dict
|
276 |
+
|
277 |
+
|
278 |
+
def convert_text_enc_state_dict(text_enc_dict):
|
279 |
+
return text_enc_dict
|
280 |
+
|
281 |
+
|
comfy/diffusers_load.py
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
|
3 |
+
import comfy.sd
|
4 |
+
|
5 |
+
def first_file(path, filenames):
|
6 |
+
for f in filenames:
|
7 |
+
p = os.path.join(path, f)
|
8 |
+
if os.path.exists(p):
|
9 |
+
return p
|
10 |
+
return None
|
11 |
+
|
12 |
+
def load_diffusers(model_path, output_vae=True, output_clip=True, embedding_directory=None):
|
13 |
+
diffusion_model_names = ["diffusion_pytorch_model.fp16.safetensors", "diffusion_pytorch_model.safetensors", "diffusion_pytorch_model.fp16.bin", "diffusion_pytorch_model.bin"]
|
14 |
+
unet_path = first_file(os.path.join(model_path, "unet"), diffusion_model_names)
|
15 |
+
vae_path = first_file(os.path.join(model_path, "vae"), diffusion_model_names)
|
16 |
+
|
17 |
+
text_encoder_model_names = ["model.fp16.safetensors", "model.safetensors", "pytorch_model.fp16.bin", "pytorch_model.bin"]
|
18 |
+
text_encoder1_path = first_file(os.path.join(model_path, "text_encoder"), text_encoder_model_names)
|
19 |
+
text_encoder2_path = first_file(os.path.join(model_path, "text_encoder_2"), text_encoder_model_names)
|
20 |
+
|
21 |
+
text_encoder_paths = [text_encoder1_path]
|
22 |
+
if text_encoder2_path is not None:
|
23 |
+
text_encoder_paths.append(text_encoder2_path)
|
24 |
+
|
25 |
+
unet = comfy.sd.load_unet(unet_path)
|
26 |
+
|
27 |
+
clip = None
|
28 |
+
if output_clip:
|
29 |
+
clip = comfy.sd.load_clip(text_encoder_paths, embedding_directory=embedding_directory)
|
30 |
+
|
31 |
+
vae = None
|
32 |
+
if output_vae:
|
33 |
+
sd = comfy.utils.load_torch_file(vae_path)
|
34 |
+
vae = comfy.sd.VAE(sd=sd)
|
35 |
+
|
36 |
+
return (unet, clip, vae)
|
comfy/extra_samplers/uni_pc.py
ADDED
@@ -0,0 +1,875 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#code taken from: https://github.com/wl-zhao/UniPC and modified
|
2 |
+
|
3 |
+
import torch
|
4 |
+
import torch.nn.functional as F
|
5 |
+
import math
|
6 |
+
|
7 |
+
from tqdm.auto import trange, tqdm
|
8 |
+
|
9 |
+
|
10 |
+
class NoiseScheduleVP:
|
11 |
+
def __init__(
|
12 |
+
self,
|
13 |
+
schedule='discrete',
|
14 |
+
betas=None,
|
15 |
+
alphas_cumprod=None,
|
16 |
+
continuous_beta_0=0.1,
|
17 |
+
continuous_beta_1=20.,
|
18 |
+
):
|
19 |
+
"""Create a wrapper class for the forward SDE (VP type).
|
20 |
+
|
21 |
+
***
|
22 |
+
Update: We support discrete-time diffusion models by implementing a picewise linear interpolation for log_alpha_t.
|
23 |
+
We recommend to use schedule='discrete' for the discrete-time diffusion models, especially for high-resolution images.
|
24 |
+
***
|
25 |
+
|
26 |
+
The forward SDE ensures that the condition distribution q_{t|0}(x_t | x_0) = N ( alpha_t * x_0, sigma_t^2 * I ).
|
27 |
+
We further define lambda_t = log(alpha_t) - log(sigma_t), which is the half-logSNR (described in the DPM-Solver paper).
|
28 |
+
Therefore, we implement the functions for computing alpha_t, sigma_t and lambda_t. For t in [0, T], we have:
|
29 |
+
|
30 |
+
log_alpha_t = self.marginal_log_mean_coeff(t)
|
31 |
+
sigma_t = self.marginal_std(t)
|
32 |
+
lambda_t = self.marginal_lambda(t)
|
33 |
+
|
34 |
+
Moreover, as lambda(t) is an invertible function, we also support its inverse function:
|
35 |
+
|
36 |
+
t = self.inverse_lambda(lambda_t)
|
37 |
+
|
38 |
+
===============================================================
|
39 |
+
|
40 |
+
We support both discrete-time DPMs (trained on n = 0, 1, ..., N-1) and continuous-time DPMs (trained on t in [t_0, T]).
|
41 |
+
|
42 |
+
1. For discrete-time DPMs:
|
43 |
+
|
44 |
+
For discrete-time DPMs trained on n = 0, 1, ..., N-1, we convert the discrete steps to continuous time steps by:
|
45 |
+
t_i = (i + 1) / N
|
46 |
+
e.g. for N = 1000, we have t_0 = 1e-3 and T = t_{N-1} = 1.
|
47 |
+
We solve the corresponding diffusion ODE from time T = 1 to time t_0 = 1e-3.
|
48 |
+
|
49 |
+
Args:
|
50 |
+
betas: A `torch.Tensor`. The beta array for the discrete-time DPM. (See the original DDPM paper for details)
|
51 |
+
alphas_cumprod: A `torch.Tensor`. The cumprod alphas for the discrete-time DPM. (See the original DDPM paper for details)
|
52 |
+
|
53 |
+
Note that we always have alphas_cumprod = cumprod(betas). Therefore, we only need to set one of `betas` and `alphas_cumprod`.
|
54 |
+
|
55 |
+
**Important**: Please pay special attention for the args for `alphas_cumprod`:
|
56 |
+
The `alphas_cumprod` is the \hat{alpha_n} arrays in the notations of DDPM. Specifically, DDPMs assume that
|
57 |
+
q_{t_n | 0}(x_{t_n} | x_0) = N ( \sqrt{\hat{alpha_n}} * x_0, (1 - \hat{alpha_n}) * I ).
|
58 |
+
Therefore, the notation \hat{alpha_n} is different from the notation alpha_t in DPM-Solver. In fact, we have
|
59 |
+
alpha_{t_n} = \sqrt{\hat{alpha_n}},
|
60 |
+
and
|
61 |
+
log(alpha_{t_n}) = 0.5 * log(\hat{alpha_n}).
|
62 |
+
|
63 |
+
|
64 |
+
2. For continuous-time DPMs:
|
65 |
+
|
66 |
+
We support two types of VPSDEs: linear (DDPM) and cosine (improved-DDPM). The hyperparameters for the noise
|
67 |
+
schedule are the default settings in DDPM and improved-DDPM:
|
68 |
+
|
69 |
+
Args:
|
70 |
+
beta_min: A `float` number. The smallest beta for the linear schedule.
|
71 |
+
beta_max: A `float` number. The largest beta for the linear schedule.
|
72 |
+
cosine_s: A `float` number. The hyperparameter in the cosine schedule.
|
73 |
+
cosine_beta_max: A `float` number. The hyperparameter in the cosine schedule.
|
74 |
+
T: A `float` number. The ending time of the forward process.
|
75 |
+
|
76 |
+
===============================================================
|
77 |
+
|
78 |
+
Args:
|
79 |
+
schedule: A `str`. The noise schedule of the forward SDE. 'discrete' for discrete-time DPMs,
|
80 |
+
'linear' or 'cosine' for continuous-time DPMs.
|
81 |
+
Returns:
|
82 |
+
A wrapper object of the forward SDE (VP type).
|
83 |
+
|
84 |
+
===============================================================
|
85 |
+
|
86 |
+
Example:
|
87 |
+
|
88 |
+
# For discrete-time DPMs, given betas (the beta array for n = 0, 1, ..., N - 1):
|
89 |
+
>>> ns = NoiseScheduleVP('discrete', betas=betas)
|
90 |
+
|
91 |
+
# For discrete-time DPMs, given alphas_cumprod (the \hat{alpha_n} array for n = 0, 1, ..., N - 1):
|
92 |
+
>>> ns = NoiseScheduleVP('discrete', alphas_cumprod=alphas_cumprod)
|
93 |
+
|
94 |
+
# For continuous-time DPMs (VPSDE), linear schedule:
|
95 |
+
>>> ns = NoiseScheduleVP('linear', continuous_beta_0=0.1, continuous_beta_1=20.)
|
96 |
+
|
97 |
+
"""
|
98 |
+
|
99 |
+
if schedule not in ['discrete', 'linear', 'cosine']:
|
100 |
+
raise ValueError("Unsupported noise schedule {}. The schedule needs to be 'discrete' or 'linear' or 'cosine'".format(schedule))
|
101 |
+
|
102 |
+
self.schedule = schedule
|
103 |
+
if schedule == 'discrete':
|
104 |
+
if betas is not None:
|
105 |
+
log_alphas = 0.5 * torch.log(1 - betas).cumsum(dim=0)
|
106 |
+
else:
|
107 |
+
assert alphas_cumprod is not None
|
108 |
+
log_alphas = 0.5 * torch.log(alphas_cumprod)
|
109 |
+
self.total_N = len(log_alphas)
|
110 |
+
self.T = 1.
|
111 |
+
self.t_array = torch.linspace(0., 1., self.total_N + 1)[1:].reshape((1, -1))
|
112 |
+
self.log_alpha_array = log_alphas.reshape((1, -1,))
|
113 |
+
else:
|
114 |
+
self.total_N = 1000
|
115 |
+
self.beta_0 = continuous_beta_0
|
116 |
+
self.beta_1 = continuous_beta_1
|
117 |
+
self.cosine_s = 0.008
|
118 |
+
self.cosine_beta_max = 999.
|
119 |
+
self.cosine_t_max = math.atan(self.cosine_beta_max * (1. + self.cosine_s) / math.pi) * 2. * (1. + self.cosine_s) / math.pi - self.cosine_s
|
120 |
+
self.cosine_log_alpha_0 = math.log(math.cos(self.cosine_s / (1. + self.cosine_s) * math.pi / 2.))
|
121 |
+
self.schedule = schedule
|
122 |
+
if schedule == 'cosine':
|
123 |
+
# For the cosine schedule, T = 1 will have numerical issues. So we manually set the ending time T.
|
124 |
+
# Note that T = 0.9946 may be not the optimal setting. However, we find it works well.
|
125 |
+
self.T = 0.9946
|
126 |
+
else:
|
127 |
+
self.T = 1.
|
128 |
+
|
129 |
+
def marginal_log_mean_coeff(self, t):
|
130 |
+
"""
|
131 |
+
Compute log(alpha_t) of a given continuous-time label t in [0, T].
|
132 |
+
"""
|
133 |
+
if self.schedule == 'discrete':
|
134 |
+
return interpolate_fn(t.reshape((-1, 1)), self.t_array.to(t.device), self.log_alpha_array.to(t.device)).reshape((-1))
|
135 |
+
elif self.schedule == 'linear':
|
136 |
+
return -0.25 * t ** 2 * (self.beta_1 - self.beta_0) - 0.5 * t * self.beta_0
|
137 |
+
elif self.schedule == 'cosine':
|
138 |
+
log_alpha_fn = lambda s: torch.log(torch.cos((s + self.cosine_s) / (1. + self.cosine_s) * math.pi / 2.))
|
139 |
+
log_alpha_t = log_alpha_fn(t) - self.cosine_log_alpha_0
|
140 |
+
return log_alpha_t
|
141 |
+
|
142 |
+
def marginal_alpha(self, t):
|
143 |
+
"""
|
144 |
+
Compute alpha_t of a given continuous-time label t in [0, T].
|
145 |
+
"""
|
146 |
+
return torch.exp(self.marginal_log_mean_coeff(t))
|
147 |
+
|
148 |
+
def marginal_std(self, t):
|
149 |
+
"""
|
150 |
+
Compute sigma_t of a given continuous-time label t in [0, T].
|
151 |
+
"""
|
152 |
+
return torch.sqrt(1. - torch.exp(2. * self.marginal_log_mean_coeff(t)))
|
153 |
+
|
154 |
+
def marginal_lambda(self, t):
|
155 |
+
"""
|
156 |
+
Compute lambda_t = log(alpha_t) - log(sigma_t) of a given continuous-time label t in [0, T].
|
157 |
+
"""
|
158 |
+
log_mean_coeff = self.marginal_log_mean_coeff(t)
|
159 |
+
log_std = 0.5 * torch.log(1. - torch.exp(2. * log_mean_coeff))
|
160 |
+
return log_mean_coeff - log_std
|
161 |
+
|
162 |
+
def inverse_lambda(self, lamb):
|
163 |
+
"""
|
164 |
+
Compute the continuous-time label t in [0, T] of a given half-logSNR lambda_t.
|
165 |
+
"""
|
166 |
+
if self.schedule == 'linear':
|
167 |
+
tmp = 2. * (self.beta_1 - self.beta_0) * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb))
|
168 |
+
Delta = self.beta_0**2 + tmp
|
169 |
+
return tmp / (torch.sqrt(Delta) + self.beta_0) / (self.beta_1 - self.beta_0)
|
170 |
+
elif self.schedule == 'discrete':
|
171 |
+
log_alpha = -0.5 * torch.logaddexp(torch.zeros((1,)).to(lamb.device), -2. * lamb)
|
172 |
+
t = interpolate_fn(log_alpha.reshape((-1, 1)), torch.flip(self.log_alpha_array.to(lamb.device), [1]), torch.flip(self.t_array.to(lamb.device), [1]))
|
173 |
+
return t.reshape((-1,))
|
174 |
+
else:
|
175 |
+
log_alpha = -0.5 * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb))
|
176 |
+
t_fn = lambda log_alpha_t: torch.arccos(torch.exp(log_alpha_t + self.cosine_log_alpha_0)) * 2. * (1. + self.cosine_s) / math.pi - self.cosine_s
|
177 |
+
t = t_fn(log_alpha)
|
178 |
+
return t
|
179 |
+
|
180 |
+
|
181 |
+
def model_wrapper(
|
182 |
+
model,
|
183 |
+
noise_schedule,
|
184 |
+
model_type="noise",
|
185 |
+
model_kwargs={},
|
186 |
+
guidance_type="uncond",
|
187 |
+
condition=None,
|
188 |
+
unconditional_condition=None,
|
189 |
+
guidance_scale=1.,
|
190 |
+
classifier_fn=None,
|
191 |
+
classifier_kwargs={},
|
192 |
+
):
|
193 |
+
"""Create a wrapper function for the noise prediction model.
|
194 |
+
|
195 |
+
DPM-Solver needs to solve the continuous-time diffusion ODEs. For DPMs trained on discrete-time labels, we need to
|
196 |
+
firstly wrap the model function to a noise prediction model that accepts the continuous time as the input.
|
197 |
+
|
198 |
+
We support four types of the diffusion model by setting `model_type`:
|
199 |
+
|
200 |
+
1. "noise": noise prediction model. (Trained by predicting noise).
|
201 |
+
|
202 |
+
2. "x_start": data prediction model. (Trained by predicting the data x_0 at time 0).
|
203 |
+
|
204 |
+
3. "v": velocity prediction model. (Trained by predicting the velocity).
|
205 |
+
The "v" prediction is derivation detailed in Appendix D of [1], and is used in Imagen-Video [2].
|
206 |
+
|
207 |
+
[1] Salimans, Tim, and Jonathan Ho. "Progressive distillation for fast sampling of diffusion models."
|
208 |
+
arXiv preprint arXiv:2202.00512 (2022).
|
209 |
+
[2] Ho, Jonathan, et al. "Imagen Video: High Definition Video Generation with Diffusion Models."
|
210 |
+
arXiv preprint arXiv:2210.02303 (2022).
|
211 |
+
|
212 |
+
4. "score": marginal score function. (Trained by denoising score matching).
|
213 |
+
Note that the score function and the noise prediction model follows a simple relationship:
|
214 |
+
```
|
215 |
+
noise(x_t, t) = -sigma_t * score(x_t, t)
|
216 |
+
```
|
217 |
+
|
218 |
+
We support three types of guided sampling by DPMs by setting `guidance_type`:
|
219 |
+
1. "uncond": unconditional sampling by DPMs.
|
220 |
+
The input `model` has the following format:
|
221 |
+
``
|
222 |
+
model(x, t_input, **model_kwargs) -> noise | x_start | v | score
|
223 |
+
``
|
224 |
+
|
225 |
+
2. "classifier": classifier guidance sampling [3] by DPMs and another classifier.
|
226 |
+
The input `model` has the following format:
|
227 |
+
``
|
228 |
+
model(x, t_input, **model_kwargs) -> noise | x_start | v | score
|
229 |
+
``
|
230 |
+
|
231 |
+
The input `classifier_fn` has the following format:
|
232 |
+
``
|
233 |
+
classifier_fn(x, t_input, cond, **classifier_kwargs) -> logits(x, t_input, cond)
|
234 |
+
``
|
235 |
+
|
236 |
+
[3] P. Dhariwal and A. Q. Nichol, "Diffusion models beat GANs on image synthesis,"
|
237 |
+
in Advances in Neural Information Processing Systems, vol. 34, 2021, pp. 8780-8794.
|
238 |
+
|
239 |
+
3. "classifier-free": classifier-free guidance sampling by conditional DPMs.
|
240 |
+
The input `model` has the following format:
|
241 |
+
``
|
242 |
+
model(x, t_input, cond, **model_kwargs) -> noise | x_start | v | score
|
243 |
+
``
|
244 |
+
And if cond == `unconditional_condition`, the model output is the unconditional DPM output.
|
245 |
+
|
246 |
+
[4] Ho, Jonathan, and Tim Salimans. "Classifier-free diffusion guidance."
|
247 |
+
arXiv preprint arXiv:2207.12598 (2022).
|
248 |
+
|
249 |
+
|
250 |
+
The `t_input` is the time label of the model, which may be discrete-time labels (i.e. 0 to 999)
|
251 |
+
or continuous-time labels (i.e. epsilon to T).
|
252 |
+
|
253 |
+
We wrap the model function to accept only `x` and `t_continuous` as inputs, and outputs the predicted noise:
|
254 |
+
``
|
255 |
+
def model_fn(x, t_continuous) -> noise:
|
256 |
+
t_input = get_model_input_time(t_continuous)
|
257 |
+
return noise_pred(model, x, t_input, **model_kwargs)
|
258 |
+
``
|
259 |
+
where `t_continuous` is the continuous time labels (i.e. epsilon to T). And we use `model_fn` for DPM-Solver.
|
260 |
+
|
261 |
+
===============================================================
|
262 |
+
|
263 |
+
Args:
|
264 |
+
model: A diffusion model with the corresponding format described above.
|
265 |
+
noise_schedule: A noise schedule object, such as NoiseScheduleVP.
|
266 |
+
model_type: A `str`. The parameterization type of the diffusion model.
|
267 |
+
"noise" or "x_start" or "v" or "score".
|
268 |
+
model_kwargs: A `dict`. A dict for the other inputs of the model function.
|
269 |
+
guidance_type: A `str`. The type of the guidance for sampling.
|
270 |
+
"uncond" or "classifier" or "classifier-free".
|
271 |
+
condition: A pytorch tensor. The condition for the guided sampling.
|
272 |
+
Only used for "classifier" or "classifier-free" guidance type.
|
273 |
+
unconditional_condition: A pytorch tensor. The condition for the unconditional sampling.
|
274 |
+
Only used for "classifier-free" guidance type.
|
275 |
+
guidance_scale: A `float`. The scale for the guided sampling.
|
276 |
+
classifier_fn: A classifier function. Only used for the classifier guidance.
|
277 |
+
classifier_kwargs: A `dict`. A dict for the other inputs of the classifier function.
|
278 |
+
Returns:
|
279 |
+
A noise prediction model that accepts the noised data and the continuous time as the inputs.
|
280 |
+
"""
|
281 |
+
|
282 |
+
def get_model_input_time(t_continuous):
|
283 |
+
"""
|
284 |
+
Convert the continuous-time `t_continuous` (in [epsilon, T]) to the model input time.
|
285 |
+
For discrete-time DPMs, we convert `t_continuous` in [1 / N, 1] to `t_input` in [0, 1000 * (N - 1) / N].
|
286 |
+
For continuous-time DPMs, we just use `t_continuous`.
|
287 |
+
"""
|
288 |
+
if noise_schedule.schedule == 'discrete':
|
289 |
+
return (t_continuous - 1. / noise_schedule.total_N) * 1000.
|
290 |
+
else:
|
291 |
+
return t_continuous
|
292 |
+
|
293 |
+
def noise_pred_fn(x, t_continuous, cond=None):
|
294 |
+
if t_continuous.reshape((-1,)).shape[0] == 1:
|
295 |
+
t_continuous = t_continuous.expand((x.shape[0]))
|
296 |
+
t_input = get_model_input_time(t_continuous)
|
297 |
+
output = model(x, t_input, **model_kwargs)
|
298 |
+
if model_type == "noise":
|
299 |
+
return output
|
300 |
+
elif model_type == "x_start":
|
301 |
+
alpha_t, sigma_t = noise_schedule.marginal_alpha(t_continuous), noise_schedule.marginal_std(t_continuous)
|
302 |
+
dims = x.dim()
|
303 |
+
return (x - expand_dims(alpha_t, dims) * output) / expand_dims(sigma_t, dims)
|
304 |
+
elif model_type == "v":
|
305 |
+
alpha_t, sigma_t = noise_schedule.marginal_alpha(t_continuous), noise_schedule.marginal_std(t_continuous)
|
306 |
+
dims = x.dim()
|
307 |
+
return expand_dims(alpha_t, dims) * output + expand_dims(sigma_t, dims) * x
|
308 |
+
elif model_type == "score":
|
309 |
+
sigma_t = noise_schedule.marginal_std(t_continuous)
|
310 |
+
dims = x.dim()
|
311 |
+
return -expand_dims(sigma_t, dims) * output
|
312 |
+
|
313 |
+
def cond_grad_fn(x, t_input):
|
314 |
+
"""
|
315 |
+
Compute the gradient of the classifier, i.e. nabla_{x} log p_t(cond | x_t).
|
316 |
+
"""
|
317 |
+
with torch.enable_grad():
|
318 |
+
x_in = x.detach().requires_grad_(True)
|
319 |
+
log_prob = classifier_fn(x_in, t_input, condition, **classifier_kwargs)
|
320 |
+
return torch.autograd.grad(log_prob.sum(), x_in)[0]
|
321 |
+
|
322 |
+
def model_fn(x, t_continuous):
|
323 |
+
"""
|
324 |
+
The noise predicition model function that is used for DPM-Solver.
|
325 |
+
"""
|
326 |
+
if t_continuous.reshape((-1,)).shape[0] == 1:
|
327 |
+
t_continuous = t_continuous.expand((x.shape[0]))
|
328 |
+
if guidance_type == "uncond":
|
329 |
+
return noise_pred_fn(x, t_continuous)
|
330 |
+
elif guidance_type == "classifier":
|
331 |
+
assert classifier_fn is not None
|
332 |
+
t_input = get_model_input_time(t_continuous)
|
333 |
+
cond_grad = cond_grad_fn(x, t_input)
|
334 |
+
sigma_t = noise_schedule.marginal_std(t_continuous)
|
335 |
+
noise = noise_pred_fn(x, t_continuous)
|
336 |
+
return noise - guidance_scale * expand_dims(sigma_t, dims=cond_grad.dim()) * cond_grad
|
337 |
+
elif guidance_type == "classifier-free":
|
338 |
+
if guidance_scale == 1. or unconditional_condition is None:
|
339 |
+
return noise_pred_fn(x, t_continuous, cond=condition)
|
340 |
+
else:
|
341 |
+
x_in = torch.cat([x] * 2)
|
342 |
+
t_in = torch.cat([t_continuous] * 2)
|
343 |
+
c_in = torch.cat([unconditional_condition, condition])
|
344 |
+
noise_uncond, noise = noise_pred_fn(x_in, t_in, cond=c_in).chunk(2)
|
345 |
+
return noise_uncond + guidance_scale * (noise - noise_uncond)
|
346 |
+
|
347 |
+
assert model_type in ["noise", "x_start", "v"]
|
348 |
+
assert guidance_type in ["uncond", "classifier", "classifier-free"]
|
349 |
+
return model_fn
|
350 |
+
|
351 |
+
|
352 |
+
class UniPC:
|
353 |
+
def __init__(
|
354 |
+
self,
|
355 |
+
model_fn,
|
356 |
+
noise_schedule,
|
357 |
+
predict_x0=True,
|
358 |
+
thresholding=False,
|
359 |
+
max_val=1.,
|
360 |
+
variant='bh1',
|
361 |
+
):
|
362 |
+
"""Construct a UniPC.
|
363 |
+
|
364 |
+
We support both data_prediction and noise_prediction.
|
365 |
+
"""
|
366 |
+
self.model = model_fn
|
367 |
+
self.noise_schedule = noise_schedule
|
368 |
+
self.variant = variant
|
369 |
+
self.predict_x0 = predict_x0
|
370 |
+
self.thresholding = thresholding
|
371 |
+
self.max_val = max_val
|
372 |
+
|
373 |
+
def dynamic_thresholding_fn(self, x0, t=None):
|
374 |
+
"""
|
375 |
+
The dynamic thresholding method.
|
376 |
+
"""
|
377 |
+
dims = x0.dim()
|
378 |
+
p = self.dynamic_thresholding_ratio
|
379 |
+
s = torch.quantile(torch.abs(x0).reshape((x0.shape[0], -1)), p, dim=1)
|
380 |
+
s = expand_dims(torch.maximum(s, self.thresholding_max_val * torch.ones_like(s).to(s.device)), dims)
|
381 |
+
x0 = torch.clamp(x0, -s, s) / s
|
382 |
+
return x0
|
383 |
+
|
384 |
+
def noise_prediction_fn(self, x, t):
|
385 |
+
"""
|
386 |
+
Return the noise prediction model.
|
387 |
+
"""
|
388 |
+
return self.model(x, t)
|
389 |
+
|
390 |
+
def data_prediction_fn(self, x, t):
|
391 |
+
"""
|
392 |
+
Return the data prediction model (with thresholding).
|
393 |
+
"""
|
394 |
+
noise = self.noise_prediction_fn(x, t)
|
395 |
+
dims = x.dim()
|
396 |
+
alpha_t, sigma_t = self.noise_schedule.marginal_alpha(t), self.noise_schedule.marginal_std(t)
|
397 |
+
x0 = (x - expand_dims(sigma_t, dims) * noise) / expand_dims(alpha_t, dims)
|
398 |
+
if self.thresholding:
|
399 |
+
p = 0.995 # A hyperparameter in the paper of "Imagen" [1].
|
400 |
+
s = torch.quantile(torch.abs(x0).reshape((x0.shape[0], -1)), p, dim=1)
|
401 |
+
s = expand_dims(torch.maximum(s, self.max_val * torch.ones_like(s).to(s.device)), dims)
|
402 |
+
x0 = torch.clamp(x0, -s, s) / s
|
403 |
+
return x0
|
404 |
+
|
405 |
+
def model_fn(self, x, t):
|
406 |
+
"""
|
407 |
+
Convert the model to the noise prediction model or the data prediction model.
|
408 |
+
"""
|
409 |
+
if self.predict_x0:
|
410 |
+
return self.data_prediction_fn(x, t)
|
411 |
+
else:
|
412 |
+
return self.noise_prediction_fn(x, t)
|
413 |
+
|
414 |
+
def get_time_steps(self, skip_type, t_T, t_0, N, device):
|
415 |
+
"""Compute the intermediate time steps for sampling.
|
416 |
+
"""
|
417 |
+
if skip_type == 'logSNR':
|
418 |
+
lambda_T = self.noise_schedule.marginal_lambda(torch.tensor(t_T).to(device))
|
419 |
+
lambda_0 = self.noise_schedule.marginal_lambda(torch.tensor(t_0).to(device))
|
420 |
+
logSNR_steps = torch.linspace(lambda_T.cpu().item(), lambda_0.cpu().item(), N + 1).to(device)
|
421 |
+
return self.noise_schedule.inverse_lambda(logSNR_steps)
|
422 |
+
elif skip_type == 'time_uniform':
|
423 |
+
return torch.linspace(t_T, t_0, N + 1).to(device)
|
424 |
+
elif skip_type == 'time_quadratic':
|
425 |
+
t_order = 2
|
426 |
+
t = torch.linspace(t_T**(1. / t_order), t_0**(1. / t_order), N + 1).pow(t_order).to(device)
|
427 |
+
return t
|
428 |
+
else:
|
429 |
+
raise ValueError("Unsupported skip_type {}, need to be 'logSNR' or 'time_uniform' or 'time_quadratic'".format(skip_type))
|
430 |
+
|
431 |
+
def get_orders_and_timesteps_for_singlestep_solver(self, steps, order, skip_type, t_T, t_0, device):
|
432 |
+
"""
|
433 |
+
Get the order of each step for sampling by the singlestep DPM-Solver.
|
434 |
+
"""
|
435 |
+
if order == 3:
|
436 |
+
K = steps // 3 + 1
|
437 |
+
if steps % 3 == 0:
|
438 |
+
orders = [3,] * (K - 2) + [2, 1]
|
439 |
+
elif steps % 3 == 1:
|
440 |
+
orders = [3,] * (K - 1) + [1]
|
441 |
+
else:
|
442 |
+
orders = [3,] * (K - 1) + [2]
|
443 |
+
elif order == 2:
|
444 |
+
if steps % 2 == 0:
|
445 |
+
K = steps // 2
|
446 |
+
orders = [2,] * K
|
447 |
+
else:
|
448 |
+
K = steps // 2 + 1
|
449 |
+
orders = [2,] * (K - 1) + [1]
|
450 |
+
elif order == 1:
|
451 |
+
K = steps
|
452 |
+
orders = [1,] * steps
|
453 |
+
else:
|
454 |
+
raise ValueError("'order' must be '1' or '2' or '3'.")
|
455 |
+
if skip_type == 'logSNR':
|
456 |
+
# To reproduce the results in DPM-Solver paper
|
457 |
+
timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, K, device)
|
458 |
+
else:
|
459 |
+
timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, steps, device)[torch.cumsum(torch.tensor([0,] + orders), 0).to(device)]
|
460 |
+
return timesteps_outer, orders
|
461 |
+
|
462 |
+
def denoise_to_zero_fn(self, x, s):
|
463 |
+
"""
|
464 |
+
Denoise at the final step, which is equivalent to solve the ODE from lambda_s to infty by first-order discretization.
|
465 |
+
"""
|
466 |
+
return self.data_prediction_fn(x, s)
|
467 |
+
|
468 |
+
def multistep_uni_pc_update(self, x, model_prev_list, t_prev_list, t, order, **kwargs):
|
469 |
+
if len(t.shape) == 0:
|
470 |
+
t = t.view(-1)
|
471 |
+
if 'bh' in self.variant:
|
472 |
+
return self.multistep_uni_pc_bh_update(x, model_prev_list, t_prev_list, t, order, **kwargs)
|
473 |
+
else:
|
474 |
+
assert self.variant == 'vary_coeff'
|
475 |
+
return self.multistep_uni_pc_vary_update(x, model_prev_list, t_prev_list, t, order, **kwargs)
|
476 |
+
|
477 |
+
def multistep_uni_pc_vary_update(self, x, model_prev_list, t_prev_list, t, order, use_corrector=True):
|
478 |
+
print(f'using unified predictor-corrector with order {order} (solver type: vary coeff)')
|
479 |
+
ns = self.noise_schedule
|
480 |
+
assert order <= len(model_prev_list)
|
481 |
+
|
482 |
+
# first compute rks
|
483 |
+
t_prev_0 = t_prev_list[-1]
|
484 |
+
lambda_prev_0 = ns.marginal_lambda(t_prev_0)
|
485 |
+
lambda_t = ns.marginal_lambda(t)
|
486 |
+
model_prev_0 = model_prev_list[-1]
|
487 |
+
sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t)
|
488 |
+
log_alpha_t = ns.marginal_log_mean_coeff(t)
|
489 |
+
alpha_t = torch.exp(log_alpha_t)
|
490 |
+
|
491 |
+
h = lambda_t - lambda_prev_0
|
492 |
+
|
493 |
+
rks = []
|
494 |
+
D1s = []
|
495 |
+
for i in range(1, order):
|
496 |
+
t_prev_i = t_prev_list[-(i + 1)]
|
497 |
+
model_prev_i = model_prev_list[-(i + 1)]
|
498 |
+
lambda_prev_i = ns.marginal_lambda(t_prev_i)
|
499 |
+
rk = (lambda_prev_i - lambda_prev_0) / h
|
500 |
+
rks.append(rk)
|
501 |
+
D1s.append((model_prev_i - model_prev_0) / rk)
|
502 |
+
|
503 |
+
rks.append(1.)
|
504 |
+
rks = torch.tensor(rks, device=x.device)
|
505 |
+
|
506 |
+
K = len(rks)
|
507 |
+
# build C matrix
|
508 |
+
C = []
|
509 |
+
|
510 |
+
col = torch.ones_like(rks)
|
511 |
+
for k in range(1, K + 1):
|
512 |
+
C.append(col)
|
513 |
+
col = col * rks / (k + 1)
|
514 |
+
C = torch.stack(C, dim=1)
|
515 |
+
|
516 |
+
if len(D1s) > 0:
|
517 |
+
D1s = torch.stack(D1s, dim=1) # (B, K)
|
518 |
+
C_inv_p = torch.linalg.inv(C[:-1, :-1])
|
519 |
+
A_p = C_inv_p
|
520 |
+
|
521 |
+
if use_corrector:
|
522 |
+
print('using corrector')
|
523 |
+
C_inv = torch.linalg.inv(C)
|
524 |
+
A_c = C_inv
|
525 |
+
|
526 |
+
hh = -h if self.predict_x0 else h
|
527 |
+
h_phi_1 = torch.expm1(hh)
|
528 |
+
h_phi_ks = []
|
529 |
+
factorial_k = 1
|
530 |
+
h_phi_k = h_phi_1
|
531 |
+
for k in range(1, K + 2):
|
532 |
+
h_phi_ks.append(h_phi_k)
|
533 |
+
h_phi_k = h_phi_k / hh - 1 / factorial_k
|
534 |
+
factorial_k *= (k + 1)
|
535 |
+
|
536 |
+
model_t = None
|
537 |
+
if self.predict_x0:
|
538 |
+
x_t_ = (
|
539 |
+
sigma_t / sigma_prev_0 * x
|
540 |
+
- alpha_t * h_phi_1 * model_prev_0
|
541 |
+
)
|
542 |
+
# now predictor
|
543 |
+
x_t = x_t_
|
544 |
+
if len(D1s) > 0:
|
545 |
+
# compute the residuals for predictor
|
546 |
+
for k in range(K - 1):
|
547 |
+
x_t = x_t - alpha_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_p[k])
|
548 |
+
# now corrector
|
549 |
+
if use_corrector:
|
550 |
+
model_t = self.model_fn(x_t, t)
|
551 |
+
D1_t = (model_t - model_prev_0)
|
552 |
+
x_t = x_t_
|
553 |
+
k = 0
|
554 |
+
for k in range(K - 1):
|
555 |
+
x_t = x_t - alpha_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_c[k][:-1])
|
556 |
+
x_t = x_t - alpha_t * h_phi_ks[K] * (D1_t * A_c[k][-1])
|
557 |
+
else:
|
558 |
+
log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t)
|
559 |
+
x_t_ = (
|
560 |
+
(torch.exp(log_alpha_t - log_alpha_prev_0)) * x
|
561 |
+
- (sigma_t * h_phi_1) * model_prev_0
|
562 |
+
)
|
563 |
+
# now predictor
|
564 |
+
x_t = x_t_
|
565 |
+
if len(D1s) > 0:
|
566 |
+
# compute the residuals for predictor
|
567 |
+
for k in range(K - 1):
|
568 |
+
x_t = x_t - sigma_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_p[k])
|
569 |
+
# now corrector
|
570 |
+
if use_corrector:
|
571 |
+
model_t = self.model_fn(x_t, t)
|
572 |
+
D1_t = (model_t - model_prev_0)
|
573 |
+
x_t = x_t_
|
574 |
+
k = 0
|
575 |
+
for k in range(K - 1):
|
576 |
+
x_t = x_t - sigma_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_c[k][:-1])
|
577 |
+
x_t = x_t - sigma_t * h_phi_ks[K] * (D1_t * A_c[k][-1])
|
578 |
+
return x_t, model_t
|
579 |
+
|
580 |
+
def multistep_uni_pc_bh_update(self, x, model_prev_list, t_prev_list, t, order, x_t=None, use_corrector=True):
|
581 |
+
# print(f'using unified predictor-corrector with order {order} (solver type: B(h))')
|
582 |
+
ns = self.noise_schedule
|
583 |
+
assert order <= len(model_prev_list)
|
584 |
+
dims = x.dim()
|
585 |
+
|
586 |
+
# first compute rks
|
587 |
+
t_prev_0 = t_prev_list[-1]
|
588 |
+
lambda_prev_0 = ns.marginal_lambda(t_prev_0)
|
589 |
+
lambda_t = ns.marginal_lambda(t)
|
590 |
+
model_prev_0 = model_prev_list[-1]
|
591 |
+
sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t)
|
592 |
+
log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t)
|
593 |
+
alpha_t = torch.exp(log_alpha_t)
|
594 |
+
|
595 |
+
h = lambda_t - lambda_prev_0
|
596 |
+
|
597 |
+
rks = []
|
598 |
+
D1s = []
|
599 |
+
for i in range(1, order):
|
600 |
+
t_prev_i = t_prev_list[-(i + 1)]
|
601 |
+
model_prev_i = model_prev_list[-(i + 1)]
|
602 |
+
lambda_prev_i = ns.marginal_lambda(t_prev_i)
|
603 |
+
rk = ((lambda_prev_i - lambda_prev_0) / h)[0]
|
604 |
+
rks.append(rk)
|
605 |
+
D1s.append((model_prev_i - model_prev_0) / rk)
|
606 |
+
|
607 |
+
rks.append(1.)
|
608 |
+
rks = torch.tensor(rks, device=x.device)
|
609 |
+
|
610 |
+
R = []
|
611 |
+
b = []
|
612 |
+
|
613 |
+
hh = -h[0] if self.predict_x0 else h[0]
|
614 |
+
h_phi_1 = torch.expm1(hh) # h\phi_1(h) = e^h - 1
|
615 |
+
h_phi_k = h_phi_1 / hh - 1
|
616 |
+
|
617 |
+
factorial_i = 1
|
618 |
+
|
619 |
+
if self.variant == 'bh1':
|
620 |
+
B_h = hh
|
621 |
+
elif self.variant == 'bh2':
|
622 |
+
B_h = torch.expm1(hh)
|
623 |
+
else:
|
624 |
+
raise NotImplementedError()
|
625 |
+
|
626 |
+
for i in range(1, order + 1):
|
627 |
+
R.append(torch.pow(rks, i - 1))
|
628 |
+
b.append(h_phi_k * factorial_i / B_h)
|
629 |
+
factorial_i *= (i + 1)
|
630 |
+
h_phi_k = h_phi_k / hh - 1 / factorial_i
|
631 |
+
|
632 |
+
R = torch.stack(R)
|
633 |
+
b = torch.tensor(b, device=x.device)
|
634 |
+
|
635 |
+
# now predictor
|
636 |
+
use_predictor = len(D1s) > 0 and x_t is None
|
637 |
+
if len(D1s) > 0:
|
638 |
+
D1s = torch.stack(D1s, dim=1) # (B, K)
|
639 |
+
if x_t is None:
|
640 |
+
# for order 2, we use a simplified version
|
641 |
+
if order == 2:
|
642 |
+
rhos_p = torch.tensor([0.5], device=b.device)
|
643 |
+
else:
|
644 |
+
rhos_p = torch.linalg.solve(R[:-1, :-1], b[:-1])
|
645 |
+
else:
|
646 |
+
D1s = None
|
647 |
+
|
648 |
+
if use_corrector:
|
649 |
+
# print('using corrector')
|
650 |
+
# for order 1, we use a simplified version
|
651 |
+
if order == 1:
|
652 |
+
rhos_c = torch.tensor([0.5], device=b.device)
|
653 |
+
else:
|
654 |
+
rhos_c = torch.linalg.solve(R, b)
|
655 |
+
|
656 |
+
model_t = None
|
657 |
+
if self.predict_x0:
|
658 |
+
x_t_ = (
|
659 |
+
expand_dims(sigma_t / sigma_prev_0, dims) * x
|
660 |
+
- expand_dims(alpha_t * h_phi_1, dims)* model_prev_0
|
661 |
+
)
|
662 |
+
|
663 |
+
if x_t is None:
|
664 |
+
if use_predictor:
|
665 |
+
pred_res = torch.einsum('k,bkchw->bchw', rhos_p, D1s)
|
666 |
+
else:
|
667 |
+
pred_res = 0
|
668 |
+
x_t = x_t_ - expand_dims(alpha_t * B_h, dims) * pred_res
|
669 |
+
|
670 |
+
if use_corrector:
|
671 |
+
model_t = self.model_fn(x_t, t)
|
672 |
+
if D1s is not None:
|
673 |
+
corr_res = torch.einsum('k,bkchw->bchw', rhos_c[:-1], D1s)
|
674 |
+
else:
|
675 |
+
corr_res = 0
|
676 |
+
D1_t = (model_t - model_prev_0)
|
677 |
+
x_t = x_t_ - expand_dims(alpha_t * B_h, dims) * (corr_res + rhos_c[-1] * D1_t)
|
678 |
+
else:
|
679 |
+
x_t_ = (
|
680 |
+
expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x
|
681 |
+
- expand_dims(sigma_t * h_phi_1, dims) * model_prev_0
|
682 |
+
)
|
683 |
+
if x_t is None:
|
684 |
+
if use_predictor:
|
685 |
+
pred_res = torch.einsum('k,bkchw->bchw', rhos_p, D1s)
|
686 |
+
else:
|
687 |
+
pred_res = 0
|
688 |
+
x_t = x_t_ - expand_dims(sigma_t * B_h, dims) * pred_res
|
689 |
+
|
690 |
+
if use_corrector:
|
691 |
+
model_t = self.model_fn(x_t, t)
|
692 |
+
if D1s is not None:
|
693 |
+
corr_res = torch.einsum('k,bkchw->bchw', rhos_c[:-1], D1s)
|
694 |
+
else:
|
695 |
+
corr_res = 0
|
696 |
+
D1_t = (model_t - model_prev_0)
|
697 |
+
x_t = x_t_ - expand_dims(sigma_t * B_h, dims) * (corr_res + rhos_c[-1] * D1_t)
|
698 |
+
return x_t, model_t
|
699 |
+
|
700 |
+
|
701 |
+
def sample(self, x, timesteps, t_start=None, t_end=None, order=3, skip_type='time_uniform',
|
702 |
+
method='singlestep', lower_order_final=True, denoise_to_zero=False, solver_type='dpm_solver',
|
703 |
+
atol=0.0078, rtol=0.05, corrector=False, callback=None, disable_pbar=False
|
704 |
+
):
|
705 |
+
# t_0 = 1. / self.noise_schedule.total_N if t_end is None else t_end
|
706 |
+
# t_T = self.noise_schedule.T if t_start is None else t_start
|
707 |
+
device = x.device
|
708 |
+
steps = len(timesteps) - 1
|
709 |
+
if method == 'multistep':
|
710 |
+
assert steps >= order
|
711 |
+
# timesteps = self.get_time_steps(skip_type=skip_type, t_T=t_T, t_0=t_0, N=steps, device=device)
|
712 |
+
assert timesteps.shape[0] - 1 == steps
|
713 |
+
# with torch.no_grad():
|
714 |
+
for step_index in trange(steps, disable=disable_pbar):
|
715 |
+
if step_index == 0:
|
716 |
+
vec_t = timesteps[0].expand((x.shape[0]))
|
717 |
+
model_prev_list = [self.model_fn(x, vec_t)]
|
718 |
+
t_prev_list = [vec_t]
|
719 |
+
elif step_index < order:
|
720 |
+
init_order = step_index
|
721 |
+
# Init the first `order` values by lower order multistep DPM-Solver.
|
722 |
+
# for init_order in range(1, order):
|
723 |
+
vec_t = timesteps[init_order].expand(x.shape[0])
|
724 |
+
x, model_x = self.multistep_uni_pc_update(x, model_prev_list, t_prev_list, vec_t, init_order, use_corrector=True)
|
725 |
+
if model_x is None:
|
726 |
+
model_x = self.model_fn(x, vec_t)
|
727 |
+
model_prev_list.append(model_x)
|
728 |
+
t_prev_list.append(vec_t)
|
729 |
+
else:
|
730 |
+
extra_final_step = 0
|
731 |
+
if step_index == (steps - 1):
|
732 |
+
extra_final_step = 1
|
733 |
+
for step in range(step_index, step_index + 1 + extra_final_step):
|
734 |
+
vec_t = timesteps[step].expand(x.shape[0])
|
735 |
+
if lower_order_final:
|
736 |
+
step_order = min(order, steps + 1 - step)
|
737 |
+
else:
|
738 |
+
step_order = order
|
739 |
+
# print('this step order:', step_order)
|
740 |
+
if step == steps:
|
741 |
+
# print('do not run corrector at the last step')
|
742 |
+
use_corrector = False
|
743 |
+
else:
|
744 |
+
use_corrector = True
|
745 |
+
x, model_x = self.multistep_uni_pc_update(x, model_prev_list, t_prev_list, vec_t, step_order, use_corrector=use_corrector)
|
746 |
+
for i in range(order - 1):
|
747 |
+
t_prev_list[i] = t_prev_list[i + 1]
|
748 |
+
model_prev_list[i] = model_prev_list[i + 1]
|
749 |
+
t_prev_list[-1] = vec_t
|
750 |
+
# We do not need to evaluate the final model value.
|
751 |
+
if step < steps:
|
752 |
+
if model_x is None:
|
753 |
+
model_x = self.model_fn(x, vec_t)
|
754 |
+
model_prev_list[-1] = model_x
|
755 |
+
if callback is not None:
|
756 |
+
callback({'x': x, 'i': step_index, 'denoised': model_prev_list[-1]})
|
757 |
+
else:
|
758 |
+
raise NotImplementedError()
|
759 |
+
# if denoise_to_zero:
|
760 |
+
# x = self.denoise_to_zero_fn(x, torch.ones((x.shape[0],)).to(device) * t_0)
|
761 |
+
return x
|
762 |
+
|
763 |
+
|
764 |
+
#############################################################
|
765 |
+
# other utility functions
|
766 |
+
#############################################################
|
767 |
+
|
768 |
+
def interpolate_fn(x, xp, yp):
|
769 |
+
"""
|
770 |
+
A piecewise linear function y = f(x), using xp and yp as keypoints.
|
771 |
+
We implement f(x) in a differentiable way (i.e. applicable for autograd).
|
772 |
+
The function f(x) is well-defined for all x-axis. (For x beyond the bounds of xp, we use the outmost points of xp to define the linear function.)
|
773 |
+
|
774 |
+
Args:
|
775 |
+
x: PyTorch tensor with shape [N, C], where N is the batch size, C is the number of channels (we use C = 1 for DPM-Solver).
|
776 |
+
xp: PyTorch tensor with shape [C, K], where K is the number of keypoints.
|
777 |
+
yp: PyTorch tensor with shape [C, K].
|
778 |
+
Returns:
|
779 |
+
The function values f(x), with shape [N, C].
|
780 |
+
"""
|
781 |
+
N, K = x.shape[0], xp.shape[1]
|
782 |
+
all_x = torch.cat([x.unsqueeze(2), xp.unsqueeze(0).repeat((N, 1, 1))], dim=2)
|
783 |
+
sorted_all_x, x_indices = torch.sort(all_x, dim=2)
|
784 |
+
x_idx = torch.argmin(x_indices, dim=2)
|
785 |
+
cand_start_idx = x_idx - 1
|
786 |
+
start_idx = torch.where(
|
787 |
+
torch.eq(x_idx, 0),
|
788 |
+
torch.tensor(1, device=x.device),
|
789 |
+
torch.where(
|
790 |
+
torch.eq(x_idx, K), torch.tensor(K - 2, device=x.device), cand_start_idx,
|
791 |
+
),
|
792 |
+
)
|
793 |
+
end_idx = torch.where(torch.eq(start_idx, cand_start_idx), start_idx + 2, start_idx + 1)
|
794 |
+
start_x = torch.gather(sorted_all_x, dim=2, index=start_idx.unsqueeze(2)).squeeze(2)
|
795 |
+
end_x = torch.gather(sorted_all_x, dim=2, index=end_idx.unsqueeze(2)).squeeze(2)
|
796 |
+
start_idx2 = torch.where(
|
797 |
+
torch.eq(x_idx, 0),
|
798 |
+
torch.tensor(0, device=x.device),
|
799 |
+
torch.where(
|
800 |
+
torch.eq(x_idx, K), torch.tensor(K - 2, device=x.device), cand_start_idx,
|
801 |
+
),
|
802 |
+
)
|
803 |
+
y_positions_expanded = yp.unsqueeze(0).expand(N, -1, -1)
|
804 |
+
start_y = torch.gather(y_positions_expanded, dim=2, index=start_idx2.unsqueeze(2)).squeeze(2)
|
805 |
+
end_y = torch.gather(y_positions_expanded, dim=2, index=(start_idx2 + 1).unsqueeze(2)).squeeze(2)
|
806 |
+
cand = start_y + (x - start_x) * (end_y - start_y) / (end_x - start_x)
|
807 |
+
return cand
|
808 |
+
|
809 |
+
|
810 |
+
def expand_dims(v, dims):
|
811 |
+
"""
|
812 |
+
Expand the tensor `v` to the dim `dims`.
|
813 |
+
|
814 |
+
Args:
|
815 |
+
`v`: a PyTorch tensor with shape [N].
|
816 |
+
`dim`: a `int`.
|
817 |
+
Returns:
|
818 |
+
a PyTorch tensor with shape [N, 1, 1, ..., 1] and the total dimension is `dims`.
|
819 |
+
"""
|
820 |
+
return v[(...,) + (None,)*(dims - 1)]
|
821 |
+
|
822 |
+
|
823 |
+
class SigmaConvert:
|
824 |
+
schedule = ""
|
825 |
+
def marginal_log_mean_coeff(self, sigma):
|
826 |
+
return 0.5 * torch.log(1 / ((sigma * sigma) + 1))
|
827 |
+
|
828 |
+
def marginal_alpha(self, t):
|
829 |
+
return torch.exp(self.marginal_log_mean_coeff(t))
|
830 |
+
|
831 |
+
def marginal_std(self, t):
|
832 |
+
return torch.sqrt(1. - torch.exp(2. * self.marginal_log_mean_coeff(t)))
|
833 |
+
|
834 |
+
def marginal_lambda(self, t):
|
835 |
+
"""
|
836 |
+
Compute lambda_t = log(alpha_t) - log(sigma_t) of a given continuous-time label t in [0, T].
|
837 |
+
"""
|
838 |
+
log_mean_coeff = self.marginal_log_mean_coeff(t)
|
839 |
+
log_std = 0.5 * torch.log(1. - torch.exp(2. * log_mean_coeff))
|
840 |
+
return log_mean_coeff - log_std
|
841 |
+
|
842 |
+
def predict_eps_sigma(model, input, sigma_in, **kwargs):
|
843 |
+
sigma = sigma_in.view(sigma_in.shape[:1] + (1,) * (input.ndim - 1))
|
844 |
+
input = input * ((sigma ** 2 + 1.0) ** 0.5)
|
845 |
+
return (input - model(input, sigma_in, **kwargs)) / sigma
|
846 |
+
|
847 |
+
|
848 |
+
def sample_unipc(model, noise, sigmas, extra_args=None, callback=None, disable=False, variant='bh1'):
|
849 |
+
timesteps = sigmas.clone()
|
850 |
+
if sigmas[-1] == 0:
|
851 |
+
timesteps = sigmas[:]
|
852 |
+
timesteps[-1] = 0.001
|
853 |
+
else:
|
854 |
+
timesteps = sigmas.clone()
|
855 |
+
ns = SigmaConvert()
|
856 |
+
|
857 |
+
noise = noise / torch.sqrt(1.0 + timesteps[0] ** 2.0)
|
858 |
+
model_type = "noise"
|
859 |
+
|
860 |
+
model_fn = model_wrapper(
|
861 |
+
lambda input, sigma, **kwargs: predict_eps_sigma(model, input, sigma, **kwargs),
|
862 |
+
ns,
|
863 |
+
model_type=model_type,
|
864 |
+
guidance_type="uncond",
|
865 |
+
model_kwargs=extra_args,
|
866 |
+
)
|
867 |
+
|
868 |
+
order = min(3, len(timesteps) - 2)
|
869 |
+
uni_pc = UniPC(model_fn, ns, predict_x0=True, thresholding=False, variant=variant)
|
870 |
+
x = uni_pc.sample(noise, timesteps=timesteps, skip_type="time_uniform", method="multistep", order=order, lower_order_final=True, callback=callback, disable_pbar=disable)
|
871 |
+
x /= ns.marginal_alpha(timesteps[-1])
|
872 |
+
return x
|
873 |
+
|
874 |
+
def sample_unipc_bh2(model, noise, sigmas, extra_args=None, callback=None, disable=False):
|
875 |
+
return sample_unipc(model, noise, sigmas, extra_args, callback, disable, variant='bh2')
|
comfy/gligen.py
ADDED
@@ -0,0 +1,343 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from torch import nn
|
3 |
+
from .ldm.modules.attention import CrossAttention
|
4 |
+
from inspect import isfunction
|
5 |
+
import comfy.ops
|
6 |
+
ops = comfy.ops.manual_cast
|
7 |
+
|
8 |
+
def exists(val):
|
9 |
+
return val is not None
|
10 |
+
|
11 |
+
|
12 |
+
def uniq(arr):
|
13 |
+
return{el: True for el in arr}.keys()
|
14 |
+
|
15 |
+
|
16 |
+
def default(val, d):
|
17 |
+
if exists(val):
|
18 |
+
return val
|
19 |
+
return d() if isfunction(d) else d
|
20 |
+
|
21 |
+
|
22 |
+
# feedforward
|
23 |
+
class GEGLU(nn.Module):
|
24 |
+
def __init__(self, dim_in, dim_out):
|
25 |
+
super().__init__()
|
26 |
+
self.proj = ops.Linear(dim_in, dim_out * 2)
|
27 |
+
|
28 |
+
def forward(self, x):
|
29 |
+
x, gate = self.proj(x).chunk(2, dim=-1)
|
30 |
+
return x * torch.nn.functional.gelu(gate)
|
31 |
+
|
32 |
+
|
33 |
+
class FeedForward(nn.Module):
|
34 |
+
def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.):
|
35 |
+
super().__init__()
|
36 |
+
inner_dim = int(dim * mult)
|
37 |
+
dim_out = default(dim_out, dim)
|
38 |
+
project_in = nn.Sequential(
|
39 |
+
ops.Linear(dim, inner_dim),
|
40 |
+
nn.GELU()
|
41 |
+
) if not glu else GEGLU(dim, inner_dim)
|
42 |
+
|
43 |
+
self.net = nn.Sequential(
|
44 |
+
project_in,
|
45 |
+
nn.Dropout(dropout),
|
46 |
+
ops.Linear(inner_dim, dim_out)
|
47 |
+
)
|
48 |
+
|
49 |
+
def forward(self, x):
|
50 |
+
return self.net(x)
|
51 |
+
|
52 |
+
|
53 |
+
class GatedCrossAttentionDense(nn.Module):
|
54 |
+
def __init__(self, query_dim, context_dim, n_heads, d_head):
|
55 |
+
super().__init__()
|
56 |
+
|
57 |
+
self.attn = CrossAttention(
|
58 |
+
query_dim=query_dim,
|
59 |
+
context_dim=context_dim,
|
60 |
+
heads=n_heads,
|
61 |
+
dim_head=d_head,
|
62 |
+
operations=ops)
|
63 |
+
self.ff = FeedForward(query_dim, glu=True)
|
64 |
+
|
65 |
+
self.norm1 = ops.LayerNorm(query_dim)
|
66 |
+
self.norm2 = ops.LayerNorm(query_dim)
|
67 |
+
|
68 |
+
self.register_parameter('alpha_attn', nn.Parameter(torch.tensor(0.)))
|
69 |
+
self.register_parameter('alpha_dense', nn.Parameter(torch.tensor(0.)))
|
70 |
+
|
71 |
+
# this can be useful: we can externally change magnitude of tanh(alpha)
|
72 |
+
# for example, when it is set to 0, then the entire model is same as
|
73 |
+
# original one
|
74 |
+
self.scale = 1
|
75 |
+
|
76 |
+
def forward(self, x, objs):
|
77 |
+
|
78 |
+
x = x + self.scale * \
|
79 |
+
torch.tanh(self.alpha_attn) * self.attn(self.norm1(x), objs, objs)
|
80 |
+
x = x + self.scale * \
|
81 |
+
torch.tanh(self.alpha_dense) * self.ff(self.norm2(x))
|
82 |
+
|
83 |
+
return x
|
84 |
+
|
85 |
+
|
86 |
+
class GatedSelfAttentionDense(nn.Module):
|
87 |
+
def __init__(self, query_dim, context_dim, n_heads, d_head):
|
88 |
+
super().__init__()
|
89 |
+
|
90 |
+
# we need a linear projection since we need cat visual feature and obj
|
91 |
+
# feature
|
92 |
+
self.linear = ops.Linear(context_dim, query_dim)
|
93 |
+
|
94 |
+
self.attn = CrossAttention(
|
95 |
+
query_dim=query_dim,
|
96 |
+
context_dim=query_dim,
|
97 |
+
heads=n_heads,
|
98 |
+
dim_head=d_head,
|
99 |
+
operations=ops)
|
100 |
+
self.ff = FeedForward(query_dim, glu=True)
|
101 |
+
|
102 |
+
self.norm1 = ops.LayerNorm(query_dim)
|
103 |
+
self.norm2 = ops.LayerNorm(query_dim)
|
104 |
+
|
105 |
+
self.register_parameter('alpha_attn', nn.Parameter(torch.tensor(0.)))
|
106 |
+
self.register_parameter('alpha_dense', nn.Parameter(torch.tensor(0.)))
|
107 |
+
|
108 |
+
# this can be useful: we can externally change magnitude of tanh(alpha)
|
109 |
+
# for example, when it is set to 0, then the entire model is same as
|
110 |
+
# original one
|
111 |
+
self.scale = 1
|
112 |
+
|
113 |
+
def forward(self, x, objs):
|
114 |
+
|
115 |
+
N_visual = x.shape[1]
|
116 |
+
objs = self.linear(objs)
|
117 |
+
|
118 |
+
x = x + self.scale * torch.tanh(self.alpha_attn) * self.attn(
|
119 |
+
self.norm1(torch.cat([x, objs], dim=1)))[:, 0:N_visual, :]
|
120 |
+
x = x + self.scale * \
|
121 |
+
torch.tanh(self.alpha_dense) * self.ff(self.norm2(x))
|
122 |
+
|
123 |
+
return x
|
124 |
+
|
125 |
+
|
126 |
+
class GatedSelfAttentionDense2(nn.Module):
|
127 |
+
def __init__(self, query_dim, context_dim, n_heads, d_head):
|
128 |
+
super().__init__()
|
129 |
+
|
130 |
+
# we need a linear projection since we need cat visual feature and obj
|
131 |
+
# feature
|
132 |
+
self.linear = ops.Linear(context_dim, query_dim)
|
133 |
+
|
134 |
+
self.attn = CrossAttention(
|
135 |
+
query_dim=query_dim, context_dim=query_dim, dim_head=d_head, operations=ops)
|
136 |
+
self.ff = FeedForward(query_dim, glu=True)
|
137 |
+
|
138 |
+
self.norm1 = ops.LayerNorm(query_dim)
|
139 |
+
self.norm2 = ops.LayerNorm(query_dim)
|
140 |
+
|
141 |
+
self.register_parameter('alpha_attn', nn.Parameter(torch.tensor(0.)))
|
142 |
+
self.register_parameter('alpha_dense', nn.Parameter(torch.tensor(0.)))
|
143 |
+
|
144 |
+
# this can be useful: we can externally change magnitude of tanh(alpha)
|
145 |
+
# for example, when it is set to 0, then the entire model is same as
|
146 |
+
# original one
|
147 |
+
self.scale = 1
|
148 |
+
|
149 |
+
def forward(self, x, objs):
|
150 |
+
|
151 |
+
B, N_visual, _ = x.shape
|
152 |
+
B, N_ground, _ = objs.shape
|
153 |
+
|
154 |
+
objs = self.linear(objs)
|
155 |
+
|
156 |
+
# sanity check
|
157 |
+
size_v = math.sqrt(N_visual)
|
158 |
+
size_g = math.sqrt(N_ground)
|
159 |
+
assert int(size_v) == size_v, "Visual tokens must be square rootable"
|
160 |
+
assert int(size_g) == size_g, "Grounding tokens must be square rootable"
|
161 |
+
size_v = int(size_v)
|
162 |
+
size_g = int(size_g)
|
163 |
+
|
164 |
+
# select grounding token and resize it to visual token size as residual
|
165 |
+
out = self.attn(self.norm1(torch.cat([x, objs], dim=1)))[
|
166 |
+
:, N_visual:, :]
|
167 |
+
out = out.permute(0, 2, 1).reshape(B, -1, size_g, size_g)
|
168 |
+
out = torch.nn.functional.interpolate(
|
169 |
+
out, (size_v, size_v), mode='bicubic')
|
170 |
+
residual = out.reshape(B, -1, N_visual).permute(0, 2, 1)
|
171 |
+
|
172 |
+
# add residual to visual feature
|
173 |
+
x = x + self.scale * torch.tanh(self.alpha_attn) * residual
|
174 |
+
x = x + self.scale * \
|
175 |
+
torch.tanh(self.alpha_dense) * self.ff(self.norm2(x))
|
176 |
+
|
177 |
+
return x
|
178 |
+
|
179 |
+
|
180 |
+
class FourierEmbedder():
|
181 |
+
def __init__(self, num_freqs=64, temperature=100):
|
182 |
+
|
183 |
+
self.num_freqs = num_freqs
|
184 |
+
self.temperature = temperature
|
185 |
+
self.freq_bands = temperature ** (torch.arange(num_freqs) / num_freqs)
|
186 |
+
|
187 |
+
@torch.no_grad()
|
188 |
+
def __call__(self, x, cat_dim=-1):
|
189 |
+
"x: arbitrary shape of tensor. dim: cat dim"
|
190 |
+
out = []
|
191 |
+
for freq in self.freq_bands:
|
192 |
+
out.append(torch.sin(freq * x))
|
193 |
+
out.append(torch.cos(freq * x))
|
194 |
+
return torch.cat(out, cat_dim)
|
195 |
+
|
196 |
+
|
197 |
+
class PositionNet(nn.Module):
|
198 |
+
def __init__(self, in_dim, out_dim, fourier_freqs=8):
|
199 |
+
super().__init__()
|
200 |
+
self.in_dim = in_dim
|
201 |
+
self.out_dim = out_dim
|
202 |
+
|
203 |
+
self.fourier_embedder = FourierEmbedder(num_freqs=fourier_freqs)
|
204 |
+
self.position_dim = fourier_freqs * 2 * 4 # 2 is sin&cos, 4 is xyxy
|
205 |
+
|
206 |
+
self.linears = nn.Sequential(
|
207 |
+
ops.Linear(self.in_dim + self.position_dim, 512),
|
208 |
+
nn.SiLU(),
|
209 |
+
ops.Linear(512, 512),
|
210 |
+
nn.SiLU(),
|
211 |
+
ops.Linear(512, out_dim),
|
212 |
+
)
|
213 |
+
|
214 |
+
self.null_positive_feature = torch.nn.Parameter(
|
215 |
+
torch.zeros([self.in_dim]))
|
216 |
+
self.null_position_feature = torch.nn.Parameter(
|
217 |
+
torch.zeros([self.position_dim]))
|
218 |
+
|
219 |
+
def forward(self, boxes, masks, positive_embeddings):
|
220 |
+
B, N, _ = boxes.shape
|
221 |
+
masks = masks.unsqueeze(-1)
|
222 |
+
positive_embeddings = positive_embeddings
|
223 |
+
|
224 |
+
# embedding position (it may includes padding as placeholder)
|
225 |
+
xyxy_embedding = self.fourier_embedder(boxes) # B*N*4 --> B*N*C
|
226 |
+
|
227 |
+
# learnable null embedding
|
228 |
+
positive_null = self.null_positive_feature.to(device=boxes.device, dtype=boxes.dtype).view(1, 1, -1)
|
229 |
+
xyxy_null = self.null_position_feature.to(device=boxes.device, dtype=boxes.dtype).view(1, 1, -1)
|
230 |
+
|
231 |
+
# replace padding with learnable null embedding
|
232 |
+
positive_embeddings = positive_embeddings * \
|
233 |
+
masks + (1 - masks) * positive_null
|
234 |
+
xyxy_embedding = xyxy_embedding * masks + (1 - masks) * xyxy_null
|
235 |
+
|
236 |
+
objs = self.linears(
|
237 |
+
torch.cat([positive_embeddings, xyxy_embedding], dim=-1))
|
238 |
+
assert objs.shape == torch.Size([B, N, self.out_dim])
|
239 |
+
return objs
|
240 |
+
|
241 |
+
|
242 |
+
class Gligen(nn.Module):
|
243 |
+
def __init__(self, modules, position_net, key_dim):
|
244 |
+
super().__init__()
|
245 |
+
self.module_list = nn.ModuleList(modules)
|
246 |
+
self.position_net = position_net
|
247 |
+
self.key_dim = key_dim
|
248 |
+
self.max_objs = 30
|
249 |
+
self.current_device = torch.device("cpu")
|
250 |
+
|
251 |
+
def _set_position(self, boxes, masks, positive_embeddings):
|
252 |
+
objs = self.position_net(boxes, masks, positive_embeddings)
|
253 |
+
def func(x, extra_options):
|
254 |
+
key = extra_options["transformer_index"]
|
255 |
+
module = self.module_list[key]
|
256 |
+
return module(x, objs.to(device=x.device, dtype=x.dtype))
|
257 |
+
return func
|
258 |
+
|
259 |
+
def set_position(self, latent_image_shape, position_params, device):
|
260 |
+
batch, c, h, w = latent_image_shape
|
261 |
+
masks = torch.zeros([self.max_objs], device="cpu")
|
262 |
+
boxes = []
|
263 |
+
positive_embeddings = []
|
264 |
+
for p in position_params:
|
265 |
+
x1 = (p[4]) / w
|
266 |
+
y1 = (p[3]) / h
|
267 |
+
x2 = (p[4] + p[2]) / w
|
268 |
+
y2 = (p[3] + p[1]) / h
|
269 |
+
masks[len(boxes)] = 1.0
|
270 |
+
boxes += [torch.tensor((x1, y1, x2, y2)).unsqueeze(0)]
|
271 |
+
positive_embeddings += [p[0]]
|
272 |
+
append_boxes = []
|
273 |
+
append_conds = []
|
274 |
+
if len(boxes) < self.max_objs:
|
275 |
+
append_boxes = [torch.zeros(
|
276 |
+
[self.max_objs - len(boxes), 4], device="cpu")]
|
277 |
+
append_conds = [torch.zeros(
|
278 |
+
[self.max_objs - len(boxes), self.key_dim], device="cpu")]
|
279 |
+
|
280 |
+
box_out = torch.cat(
|
281 |
+
boxes + append_boxes).unsqueeze(0).repeat(batch, 1, 1)
|
282 |
+
masks = masks.unsqueeze(0).repeat(batch, 1)
|
283 |
+
conds = torch.cat(positive_embeddings +
|
284 |
+
append_conds).unsqueeze(0).repeat(batch, 1, 1)
|
285 |
+
return self._set_position(
|
286 |
+
box_out.to(device),
|
287 |
+
masks.to(device),
|
288 |
+
conds.to(device))
|
289 |
+
|
290 |
+
def set_empty(self, latent_image_shape, device):
|
291 |
+
batch, c, h, w = latent_image_shape
|
292 |
+
masks = torch.zeros([self.max_objs], device="cpu").repeat(batch, 1)
|
293 |
+
box_out = torch.zeros([self.max_objs, 4],
|
294 |
+
device="cpu").repeat(batch, 1, 1)
|
295 |
+
conds = torch.zeros([self.max_objs, self.key_dim],
|
296 |
+
device="cpu").repeat(batch, 1, 1)
|
297 |
+
return self._set_position(
|
298 |
+
box_out.to(device),
|
299 |
+
masks.to(device),
|
300 |
+
conds.to(device))
|
301 |
+
|
302 |
+
|
303 |
+
def load_gligen(sd):
|
304 |
+
sd_k = sd.keys()
|
305 |
+
output_list = []
|
306 |
+
key_dim = 768
|
307 |
+
for a in ["input_blocks", "middle_block", "output_blocks"]:
|
308 |
+
for b in range(20):
|
309 |
+
k_temp = filter(lambda k: "{}.{}.".format(a, b)
|
310 |
+
in k and ".fuser." in k, sd_k)
|
311 |
+
k_temp = map(lambda k: (k, k.split(".fuser.")[-1]), k_temp)
|
312 |
+
|
313 |
+
n_sd = {}
|
314 |
+
for k in k_temp:
|
315 |
+
n_sd[k[1]] = sd[k[0]]
|
316 |
+
if len(n_sd) > 0:
|
317 |
+
query_dim = n_sd["linear.weight"].shape[0]
|
318 |
+
key_dim = n_sd["linear.weight"].shape[1]
|
319 |
+
|
320 |
+
if key_dim == 768: # SD1.x
|
321 |
+
n_heads = 8
|
322 |
+
d_head = query_dim // n_heads
|
323 |
+
else:
|
324 |
+
d_head = 64
|
325 |
+
n_heads = query_dim // d_head
|
326 |
+
|
327 |
+
gated = GatedSelfAttentionDense(
|
328 |
+
query_dim, key_dim, n_heads, d_head)
|
329 |
+
gated.load_state_dict(n_sd, strict=False)
|
330 |
+
output_list.append(gated)
|
331 |
+
|
332 |
+
if "position_net.null_positive_feature" in sd_k:
|
333 |
+
in_dim = sd["position_net.null_positive_feature"].shape[0]
|
334 |
+
out_dim = sd["position_net.linears.4.weight"].shape[0]
|
335 |
+
|
336 |
+
class WeightsLoader(torch.nn.Module):
|
337 |
+
pass
|
338 |
+
w = WeightsLoader()
|
339 |
+
w.position_net = PositionNet(in_dim, out_dim)
|
340 |
+
w.load_state_dict(sd, strict=False)
|
341 |
+
|
342 |
+
gligen = Gligen(output_list, w.position_net, key_dim)
|
343 |
+
return gligen
|
comfy/k_diffusion/deis.py
ADDED
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#Taken from: https://github.com/zju-pi/diff-sampler/blob/main/gits-main/solver_utils.py
|
2 |
+
#under Apache 2 license
|
3 |
+
import torch
|
4 |
+
import numpy as np
|
5 |
+
|
6 |
+
# A pytorch reimplementation of DEIS (https://github.com/qsh-zh/deis).
|
7 |
+
#############################
|
8 |
+
### Utils for DEIS solver ###
|
9 |
+
#############################
|
10 |
+
#----------------------------------------------------------------------------
|
11 |
+
# Transfer from the input time (sigma) used in EDM to that (t) used in DEIS.
|
12 |
+
|
13 |
+
def edm2t(edm_steps, epsilon_s=1e-3, sigma_min=0.002, sigma_max=80):
|
14 |
+
vp_sigma = lambda beta_d, beta_min: lambda t: (np.e ** (0.5 * beta_d * (t ** 2) + beta_min * t) - 1) ** 0.5
|
15 |
+
vp_sigma_inv = lambda beta_d, beta_min: lambda sigma: ((beta_min ** 2 + 2 * beta_d * (sigma ** 2 + 1).log()).sqrt() - beta_min) / beta_d
|
16 |
+
vp_beta_d = 2 * (np.log(torch.tensor(sigma_min).cpu() ** 2 + 1) / epsilon_s - np.log(torch.tensor(sigma_max).cpu() ** 2 + 1)) / (epsilon_s - 1)
|
17 |
+
vp_beta_min = np.log(torch.tensor(sigma_max).cpu() ** 2 + 1) - 0.5 * vp_beta_d
|
18 |
+
t_steps = vp_sigma_inv(vp_beta_d.clone().detach().cpu(), vp_beta_min.clone().detach().cpu())(edm_steps.clone().detach().cpu())
|
19 |
+
return t_steps, vp_beta_min, vp_beta_d + vp_beta_min
|
20 |
+
|
21 |
+
#----------------------------------------------------------------------------
|
22 |
+
|
23 |
+
def cal_poly(prev_t, j, taus):
|
24 |
+
poly = 1
|
25 |
+
for k in range(prev_t.shape[0]):
|
26 |
+
if k == j:
|
27 |
+
continue
|
28 |
+
poly *= (taus - prev_t[k]) / (prev_t[j] - prev_t[k])
|
29 |
+
return poly
|
30 |
+
|
31 |
+
#----------------------------------------------------------------------------
|
32 |
+
# Transfer from t to alpha_t.
|
33 |
+
|
34 |
+
def t2alpha_fn(beta_0, beta_1, t):
|
35 |
+
return torch.exp(-0.5 * t ** 2 * (beta_1 - beta_0) - t * beta_0)
|
36 |
+
|
37 |
+
#----------------------------------------------------------------------------
|
38 |
+
|
39 |
+
def cal_intergrand(beta_0, beta_1, taus):
|
40 |
+
with torch.inference_mode(mode=False):
|
41 |
+
taus = taus.clone()
|
42 |
+
beta_0 = beta_0.clone()
|
43 |
+
beta_1 = beta_1.clone()
|
44 |
+
with torch.enable_grad():
|
45 |
+
taus.requires_grad_(True)
|
46 |
+
alpha = t2alpha_fn(beta_0, beta_1, taus)
|
47 |
+
log_alpha = alpha.log()
|
48 |
+
log_alpha.sum().backward()
|
49 |
+
d_log_alpha_dtau = taus.grad
|
50 |
+
integrand = -0.5 * d_log_alpha_dtau / torch.sqrt(alpha * (1 - alpha))
|
51 |
+
return integrand
|
52 |
+
|
53 |
+
#----------------------------------------------------------------------------
|
54 |
+
|
55 |
+
def get_deis_coeff_list(t_steps, max_order, N=10000, deis_mode='tab'):
|
56 |
+
"""
|
57 |
+
Get the coefficient list for DEIS sampling.
|
58 |
+
|
59 |
+
Args:
|
60 |
+
t_steps: A pytorch tensor. The time steps for sampling.
|
61 |
+
max_order: A `int`. Maximum order of the solver. 1 <= max_order <= 4
|
62 |
+
N: A `int`. Use how many points to perform the numerical integration when deis_mode=='tab'.
|
63 |
+
deis_mode: A `str`. Select between 'tab' and 'rhoab'. Type of DEIS.
|
64 |
+
Returns:
|
65 |
+
A pytorch tensor. A batch of generated samples or sampling trajectories if return_inters=True.
|
66 |
+
"""
|
67 |
+
if deis_mode == 'tab':
|
68 |
+
t_steps, beta_0, beta_1 = edm2t(t_steps)
|
69 |
+
C = []
|
70 |
+
for i, (t_cur, t_next) in enumerate(zip(t_steps[:-1], t_steps[1:])):
|
71 |
+
order = min(i+1, max_order)
|
72 |
+
if order == 1:
|
73 |
+
C.append([])
|
74 |
+
else:
|
75 |
+
taus = torch.linspace(t_cur, t_next, N) # split the interval for integral appximation
|
76 |
+
dtau = (t_next - t_cur) / N
|
77 |
+
prev_t = t_steps[[i - k for k in range(order)]]
|
78 |
+
coeff_temp = []
|
79 |
+
integrand = cal_intergrand(beta_0, beta_1, taus)
|
80 |
+
for j in range(order):
|
81 |
+
poly = cal_poly(prev_t, j, taus)
|
82 |
+
coeff_temp.append(torch.sum(integrand * poly) * dtau)
|
83 |
+
C.append(coeff_temp)
|
84 |
+
|
85 |
+
elif deis_mode == 'rhoab':
|
86 |
+
# Analytical solution, second order
|
87 |
+
def get_def_intergral_2(a, b, start, end, c):
|
88 |
+
coeff = (end**3 - start**3) / 3 - (end**2 - start**2) * (a + b) / 2 + (end - start) * a * b
|
89 |
+
return coeff / ((c - a) * (c - b))
|
90 |
+
|
91 |
+
# Analytical solution, third order
|
92 |
+
def get_def_intergral_3(a, b, c, start, end, d):
|
93 |
+
coeff = (end**4 - start**4) / 4 - (end**3 - start**3) * (a + b + c) / 3 \
|
94 |
+
+ (end**2 - start**2) * (a*b + a*c + b*c) / 2 - (end - start) * a * b * c
|
95 |
+
return coeff / ((d - a) * (d - b) * (d - c))
|
96 |
+
|
97 |
+
C = []
|
98 |
+
for i, (t_cur, t_next) in enumerate(zip(t_steps[:-1], t_steps[1:])):
|
99 |
+
order = min(i, max_order)
|
100 |
+
if order == 0:
|
101 |
+
C.append([])
|
102 |
+
else:
|
103 |
+
prev_t = t_steps[[i - k for k in range(order+1)]]
|
104 |
+
if order == 1:
|
105 |
+
coeff_cur = ((t_next - prev_t[1])**2 - (t_cur - prev_t[1])**2) / (2 * (t_cur - prev_t[1]))
|
106 |
+
coeff_prev1 = (t_next - t_cur)**2 / (2 * (prev_t[1] - t_cur))
|
107 |
+
coeff_temp = [coeff_cur, coeff_prev1]
|
108 |
+
elif order == 2:
|
109 |
+
coeff_cur = get_def_intergral_2(prev_t[1], prev_t[2], t_cur, t_next, t_cur)
|
110 |
+
coeff_prev1 = get_def_intergral_2(t_cur, prev_t[2], t_cur, t_next, prev_t[1])
|
111 |
+
coeff_prev2 = get_def_intergral_2(t_cur, prev_t[1], t_cur, t_next, prev_t[2])
|
112 |
+
coeff_temp = [coeff_cur, coeff_prev1, coeff_prev2]
|
113 |
+
elif order == 3:
|
114 |
+
coeff_cur = get_def_intergral_3(prev_t[1], prev_t[2], prev_t[3], t_cur, t_next, t_cur)
|
115 |
+
coeff_prev1 = get_def_intergral_3(t_cur, prev_t[2], prev_t[3], t_cur, t_next, prev_t[1])
|
116 |
+
coeff_prev2 = get_def_intergral_3(t_cur, prev_t[1], prev_t[3], t_cur, t_next, prev_t[2])
|
117 |
+
coeff_prev3 = get_def_intergral_3(t_cur, prev_t[1], prev_t[2], t_cur, t_next, prev_t[3])
|
118 |
+
coeff_temp = [coeff_cur, coeff_prev1, coeff_prev2, coeff_prev3]
|
119 |
+
C.append(coeff_temp)
|
120 |
+
return C
|
121 |
+
|
comfy/k_diffusion/sampling.py
ADDED
@@ -0,0 +1,1050 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
|
3 |
+
from scipy import integrate
|
4 |
+
import torch
|
5 |
+
from torch import nn
|
6 |
+
import torchsde
|
7 |
+
from tqdm.auto import trange, tqdm
|
8 |
+
|
9 |
+
from . import utils
|
10 |
+
from . import deis
|
11 |
+
import comfy.model_patcher
|
12 |
+
|
13 |
+
def append_zero(x):
|
14 |
+
return torch.cat([x, x.new_zeros([1])])
|
15 |
+
|
16 |
+
|
17 |
+
def get_sigmas_karras(n, sigma_min, sigma_max, rho=7., device='cpu'):
|
18 |
+
"""Constructs the noise schedule of Karras et al. (2022)."""
|
19 |
+
ramp = torch.linspace(0, 1, n, device=device)
|
20 |
+
min_inv_rho = sigma_min ** (1 / rho)
|
21 |
+
max_inv_rho = sigma_max ** (1 / rho)
|
22 |
+
sigmas = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
|
23 |
+
return append_zero(sigmas).to(device)
|
24 |
+
|
25 |
+
|
26 |
+
def get_sigmas_exponential(n, sigma_min, sigma_max, device='cpu'):
|
27 |
+
"""Constructs an exponential noise schedule."""
|
28 |
+
sigmas = torch.linspace(math.log(sigma_max), math.log(sigma_min), n, device=device).exp()
|
29 |
+
return append_zero(sigmas)
|
30 |
+
|
31 |
+
|
32 |
+
def get_sigmas_polyexponential(n, sigma_min, sigma_max, rho=1., device='cpu'):
|
33 |
+
"""Constructs an polynomial in log sigma noise schedule."""
|
34 |
+
ramp = torch.linspace(1, 0, n, device=device) ** rho
|
35 |
+
sigmas = torch.exp(ramp * (math.log(sigma_max) - math.log(sigma_min)) + math.log(sigma_min))
|
36 |
+
return append_zero(sigmas)
|
37 |
+
|
38 |
+
|
39 |
+
def get_sigmas_vp(n, beta_d=19.9, beta_min=0.1, eps_s=1e-3, device='cpu'):
|
40 |
+
"""Constructs a continuous VP noise schedule."""
|
41 |
+
t = torch.linspace(1, eps_s, n, device=device)
|
42 |
+
sigmas = torch.sqrt(torch.exp(beta_d * t ** 2 / 2 + beta_min * t) - 1)
|
43 |
+
return append_zero(sigmas)
|
44 |
+
|
45 |
+
|
46 |
+
def to_d(x, sigma, denoised):
|
47 |
+
"""Converts a denoiser output to a Karras ODE derivative."""
|
48 |
+
return (x - denoised) / utils.append_dims(sigma, x.ndim)
|
49 |
+
|
50 |
+
|
51 |
+
def get_ancestral_step(sigma_from, sigma_to, eta=1.):
|
52 |
+
"""Calculates the noise level (sigma_down) to step down to and the amount
|
53 |
+
of noise to add (sigma_up) when doing an ancestral sampling step."""
|
54 |
+
if not eta:
|
55 |
+
return sigma_to, 0.
|
56 |
+
sigma_up = min(sigma_to, eta * (sigma_to ** 2 * (sigma_from ** 2 - sigma_to ** 2) / sigma_from ** 2) ** 0.5)
|
57 |
+
sigma_down = (sigma_to ** 2 - sigma_up ** 2) ** 0.5
|
58 |
+
return sigma_down, sigma_up
|
59 |
+
|
60 |
+
|
61 |
+
def default_noise_sampler(x):
|
62 |
+
return lambda sigma, sigma_next: torch.randn_like(x)
|
63 |
+
|
64 |
+
|
65 |
+
class BatchedBrownianTree:
|
66 |
+
"""A wrapper around torchsde.BrownianTree that enables batches of entropy."""
|
67 |
+
|
68 |
+
def __init__(self, x, t0, t1, seed=None, **kwargs):
|
69 |
+
self.cpu_tree = True
|
70 |
+
if "cpu" in kwargs:
|
71 |
+
self.cpu_tree = kwargs.pop("cpu")
|
72 |
+
t0, t1, self.sign = self.sort(t0, t1)
|
73 |
+
w0 = kwargs.get('w0', torch.zeros_like(x))
|
74 |
+
if seed is None:
|
75 |
+
seed = torch.randint(0, 2 ** 63 - 1, []).item()
|
76 |
+
self.batched = True
|
77 |
+
try:
|
78 |
+
assert len(seed) == x.shape[0]
|
79 |
+
w0 = w0[0]
|
80 |
+
except TypeError:
|
81 |
+
seed = [seed]
|
82 |
+
self.batched = False
|
83 |
+
if self.cpu_tree:
|
84 |
+
self.trees = [torchsde.BrownianTree(t0.cpu(), w0.cpu(), t1.cpu(), entropy=s, **kwargs) for s in seed]
|
85 |
+
else:
|
86 |
+
self.trees = [torchsde.BrownianTree(t0, w0, t1, entropy=s, **kwargs) for s in seed]
|
87 |
+
|
88 |
+
@staticmethod
|
89 |
+
def sort(a, b):
|
90 |
+
return (a, b, 1) if a < b else (b, a, -1)
|
91 |
+
|
92 |
+
def __call__(self, t0, t1):
|
93 |
+
t0, t1, sign = self.sort(t0, t1)
|
94 |
+
if self.cpu_tree:
|
95 |
+
w = torch.stack([tree(t0.cpu().float(), t1.cpu().float()).to(t0.dtype).to(t0.device) for tree in self.trees]) * (self.sign * sign)
|
96 |
+
else:
|
97 |
+
w = torch.stack([tree(t0, t1) for tree in self.trees]) * (self.sign * sign)
|
98 |
+
|
99 |
+
return w if self.batched else w[0]
|
100 |
+
|
101 |
+
|
102 |
+
class BrownianTreeNoiseSampler:
|
103 |
+
"""A noise sampler backed by a torchsde.BrownianTree.
|
104 |
+
|
105 |
+
Args:
|
106 |
+
x (Tensor): The tensor whose shape, device and dtype to use to generate
|
107 |
+
random samples.
|
108 |
+
sigma_min (float): The low end of the valid interval.
|
109 |
+
sigma_max (float): The high end of the valid interval.
|
110 |
+
seed (int or List[int]): The random seed. If a list of seeds is
|
111 |
+
supplied instead of a single integer, then the noise sampler will
|
112 |
+
use one BrownianTree per batch item, each with its own seed.
|
113 |
+
transform (callable): A function that maps sigma to the sampler's
|
114 |
+
internal timestep.
|
115 |
+
"""
|
116 |
+
|
117 |
+
def __init__(self, x, sigma_min, sigma_max, seed=None, transform=lambda x: x, cpu=False):
|
118 |
+
self.transform = transform
|
119 |
+
t0, t1 = self.transform(torch.as_tensor(sigma_min)), self.transform(torch.as_tensor(sigma_max))
|
120 |
+
self.tree = BatchedBrownianTree(x, t0, t1, seed, cpu=cpu)
|
121 |
+
|
122 |
+
def __call__(self, sigma, sigma_next):
|
123 |
+
t0, t1 = self.transform(torch.as_tensor(sigma)), self.transform(torch.as_tensor(sigma_next))
|
124 |
+
return self.tree(t0, t1) / (t1 - t0).abs().sqrt()
|
125 |
+
|
126 |
+
|
127 |
+
@torch.no_grad()
|
128 |
+
def sample_euler(model, x, sigmas, extra_args=None, callback=None, disable=None, s_churn=0., s_tmin=0., s_tmax=float('inf'), s_noise=1.):
|
129 |
+
"""Implements Algorithm 2 (Euler steps) from Karras et al. (2022)."""
|
130 |
+
extra_args = {} if extra_args is None else extra_args
|
131 |
+
s_in = x.new_ones([x.shape[0]])
|
132 |
+
for i in trange(len(sigmas) - 1, disable=disable):
|
133 |
+
if s_churn > 0:
|
134 |
+
gamma = min(s_churn / (len(sigmas) - 1), 2 ** 0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0.
|
135 |
+
sigma_hat = sigmas[i] * (gamma + 1)
|
136 |
+
else:
|
137 |
+
gamma = 0
|
138 |
+
sigma_hat = sigmas[i]
|
139 |
+
|
140 |
+
if gamma > 0:
|
141 |
+
eps = torch.randn_like(x) * s_noise
|
142 |
+
x = x + eps * (sigma_hat ** 2 - sigmas[i] ** 2) ** 0.5
|
143 |
+
denoised = model(x, sigma_hat * s_in, **extra_args)
|
144 |
+
d = to_d(x, sigma_hat, denoised)
|
145 |
+
if callback is not None:
|
146 |
+
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigma_hat, 'denoised': denoised})
|
147 |
+
dt = sigmas[i + 1] - sigma_hat
|
148 |
+
# Euler method
|
149 |
+
x = x + d * dt
|
150 |
+
return x
|
151 |
+
|
152 |
+
|
153 |
+
@torch.no_grad()
|
154 |
+
def sample_euler_ancestral(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None):
|
155 |
+
"""Ancestral sampling with Euler method steps."""
|
156 |
+
extra_args = {} if extra_args is None else extra_args
|
157 |
+
noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler
|
158 |
+
s_in = x.new_ones([x.shape[0]])
|
159 |
+
for i in trange(len(sigmas) - 1, disable=disable):
|
160 |
+
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
161 |
+
sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1], eta=eta)
|
162 |
+
if callback is not None:
|
163 |
+
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
164 |
+
d = to_d(x, sigmas[i], denoised)
|
165 |
+
# Euler method
|
166 |
+
dt = sigma_down - sigmas[i]
|
167 |
+
x = x + d * dt
|
168 |
+
if sigmas[i + 1] > 0:
|
169 |
+
x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * sigma_up
|
170 |
+
return x
|
171 |
+
|
172 |
+
|
173 |
+
@torch.no_grad()
|
174 |
+
def sample_heun(model, x, sigmas, extra_args=None, callback=None, disable=None, s_churn=0., s_tmin=0., s_tmax=float('inf'), s_noise=1.):
|
175 |
+
"""Implements Algorithm 2 (Heun steps) from Karras et al. (2022)."""
|
176 |
+
extra_args = {} if extra_args is None else extra_args
|
177 |
+
s_in = x.new_ones([x.shape[0]])
|
178 |
+
for i in trange(len(sigmas) - 1, disable=disable):
|
179 |
+
if s_churn > 0:
|
180 |
+
gamma = min(s_churn / (len(sigmas) - 1), 2 ** 0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0.
|
181 |
+
sigma_hat = sigmas[i] * (gamma + 1)
|
182 |
+
else:
|
183 |
+
gamma = 0
|
184 |
+
sigma_hat = sigmas[i]
|
185 |
+
|
186 |
+
sigma_hat = sigmas[i] * (gamma + 1)
|
187 |
+
if gamma > 0:
|
188 |
+
eps = torch.randn_like(x) * s_noise
|
189 |
+
x = x + eps * (sigma_hat ** 2 - sigmas[i] ** 2) ** 0.5
|
190 |
+
denoised = model(x, sigma_hat * s_in, **extra_args)
|
191 |
+
d = to_d(x, sigma_hat, denoised)
|
192 |
+
if callback is not None:
|
193 |
+
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigma_hat, 'denoised': denoised})
|
194 |
+
dt = sigmas[i + 1] - sigma_hat
|
195 |
+
if sigmas[i + 1] == 0:
|
196 |
+
# Euler method
|
197 |
+
x = x + d * dt
|
198 |
+
else:
|
199 |
+
# Heun's method
|
200 |
+
x_2 = x + d * dt
|
201 |
+
denoised_2 = model(x_2, sigmas[i + 1] * s_in, **extra_args)
|
202 |
+
d_2 = to_d(x_2, sigmas[i + 1], denoised_2)
|
203 |
+
d_prime = (d + d_2) / 2
|
204 |
+
x = x + d_prime * dt
|
205 |
+
return x
|
206 |
+
|
207 |
+
|
208 |
+
@torch.no_grad()
|
209 |
+
def sample_dpm_2(model, x, sigmas, extra_args=None, callback=None, disable=None, s_churn=0., s_tmin=0., s_tmax=float('inf'), s_noise=1.):
|
210 |
+
"""A sampler inspired by DPM-Solver-2 and Algorithm 2 from Karras et al. (2022)."""
|
211 |
+
extra_args = {} if extra_args is None else extra_args
|
212 |
+
s_in = x.new_ones([x.shape[0]])
|
213 |
+
for i in trange(len(sigmas) - 1, disable=disable):
|
214 |
+
if s_churn > 0:
|
215 |
+
gamma = min(s_churn / (len(sigmas) - 1), 2 ** 0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0.
|
216 |
+
sigma_hat = sigmas[i] * (gamma + 1)
|
217 |
+
else:
|
218 |
+
gamma = 0
|
219 |
+
sigma_hat = sigmas[i]
|
220 |
+
|
221 |
+
if gamma > 0:
|
222 |
+
eps = torch.randn_like(x) * s_noise
|
223 |
+
x = x + eps * (sigma_hat ** 2 - sigmas[i] ** 2) ** 0.5
|
224 |
+
denoised = model(x, sigma_hat * s_in, **extra_args)
|
225 |
+
d = to_d(x, sigma_hat, denoised)
|
226 |
+
if callback is not None:
|
227 |
+
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigma_hat, 'denoised': denoised})
|
228 |
+
if sigmas[i + 1] == 0:
|
229 |
+
# Euler method
|
230 |
+
dt = sigmas[i + 1] - sigma_hat
|
231 |
+
x = x + d * dt
|
232 |
+
else:
|
233 |
+
# DPM-Solver-2
|
234 |
+
sigma_mid = sigma_hat.log().lerp(sigmas[i + 1].log(), 0.5).exp()
|
235 |
+
dt_1 = sigma_mid - sigma_hat
|
236 |
+
dt_2 = sigmas[i + 1] - sigma_hat
|
237 |
+
x_2 = x + d * dt_1
|
238 |
+
denoised_2 = model(x_2, sigma_mid * s_in, **extra_args)
|
239 |
+
d_2 = to_d(x_2, sigma_mid, denoised_2)
|
240 |
+
x = x + d_2 * dt_2
|
241 |
+
return x
|
242 |
+
|
243 |
+
|
244 |
+
@torch.no_grad()
|
245 |
+
def sample_dpm_2_ancestral(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None):
|
246 |
+
"""Ancestral sampling with DPM-Solver second-order steps."""
|
247 |
+
extra_args = {} if extra_args is None else extra_args
|
248 |
+
noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler
|
249 |
+
s_in = x.new_ones([x.shape[0]])
|
250 |
+
for i in trange(len(sigmas) - 1, disable=disable):
|
251 |
+
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
252 |
+
sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1], eta=eta)
|
253 |
+
if callback is not None:
|
254 |
+
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
255 |
+
d = to_d(x, sigmas[i], denoised)
|
256 |
+
if sigma_down == 0:
|
257 |
+
# Euler method
|
258 |
+
dt = sigma_down - sigmas[i]
|
259 |
+
x = x + d * dt
|
260 |
+
else:
|
261 |
+
# DPM-Solver-2
|
262 |
+
sigma_mid = sigmas[i].log().lerp(sigma_down.log(), 0.5).exp()
|
263 |
+
dt_1 = sigma_mid - sigmas[i]
|
264 |
+
dt_2 = sigma_down - sigmas[i]
|
265 |
+
x_2 = x + d * dt_1
|
266 |
+
denoised_2 = model(x_2, sigma_mid * s_in, **extra_args)
|
267 |
+
d_2 = to_d(x_2, sigma_mid, denoised_2)
|
268 |
+
x = x + d_2 * dt_2
|
269 |
+
x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * sigma_up
|
270 |
+
return x
|
271 |
+
|
272 |
+
|
273 |
+
def linear_multistep_coeff(order, t, i, j):
|
274 |
+
if order - 1 > i:
|
275 |
+
raise ValueError(f'Order {order} too high for step {i}')
|
276 |
+
def fn(tau):
|
277 |
+
prod = 1.
|
278 |
+
for k in range(order):
|
279 |
+
if j == k:
|
280 |
+
continue
|
281 |
+
prod *= (tau - t[i - k]) / (t[i - j] - t[i - k])
|
282 |
+
return prod
|
283 |
+
return integrate.quad(fn, t[i], t[i + 1], epsrel=1e-4)[0]
|
284 |
+
|
285 |
+
|
286 |
+
@torch.no_grad()
|
287 |
+
def sample_lms(model, x, sigmas, extra_args=None, callback=None, disable=None, order=4):
|
288 |
+
extra_args = {} if extra_args is None else extra_args
|
289 |
+
s_in = x.new_ones([x.shape[0]])
|
290 |
+
sigmas_cpu = sigmas.detach().cpu().numpy()
|
291 |
+
ds = []
|
292 |
+
for i in trange(len(sigmas) - 1, disable=disable):
|
293 |
+
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
294 |
+
d = to_d(x, sigmas[i], denoised)
|
295 |
+
ds.append(d)
|
296 |
+
if len(ds) > order:
|
297 |
+
ds.pop(0)
|
298 |
+
if callback is not None:
|
299 |
+
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
300 |
+
cur_order = min(i + 1, order)
|
301 |
+
coeffs = [linear_multistep_coeff(cur_order, sigmas_cpu, i, j) for j in range(cur_order)]
|
302 |
+
x = x + sum(coeff * d for coeff, d in zip(coeffs, reversed(ds)))
|
303 |
+
return x
|
304 |
+
|
305 |
+
|
306 |
+
class PIDStepSizeController:
|
307 |
+
"""A PID controller for ODE adaptive step size control."""
|
308 |
+
def __init__(self, h, pcoeff, icoeff, dcoeff, order=1, accept_safety=0.81, eps=1e-8):
|
309 |
+
self.h = h
|
310 |
+
self.b1 = (pcoeff + icoeff + dcoeff) / order
|
311 |
+
self.b2 = -(pcoeff + 2 * dcoeff) / order
|
312 |
+
self.b3 = dcoeff / order
|
313 |
+
self.accept_safety = accept_safety
|
314 |
+
self.eps = eps
|
315 |
+
self.errs = []
|
316 |
+
|
317 |
+
def limiter(self, x):
|
318 |
+
return 1 + math.atan(x - 1)
|
319 |
+
|
320 |
+
def propose_step(self, error):
|
321 |
+
inv_error = 1 / (float(error) + self.eps)
|
322 |
+
if not self.errs:
|
323 |
+
self.errs = [inv_error, inv_error, inv_error]
|
324 |
+
self.errs[0] = inv_error
|
325 |
+
factor = self.errs[0] ** self.b1 * self.errs[1] ** self.b2 * self.errs[2] ** self.b3
|
326 |
+
factor = self.limiter(factor)
|
327 |
+
accept = factor >= self.accept_safety
|
328 |
+
if accept:
|
329 |
+
self.errs[2] = self.errs[1]
|
330 |
+
self.errs[1] = self.errs[0]
|
331 |
+
self.h *= factor
|
332 |
+
return accept
|
333 |
+
|
334 |
+
|
335 |
+
class DPMSolver(nn.Module):
|
336 |
+
"""DPM-Solver. See https://arxiv.org/abs/2206.00927."""
|
337 |
+
|
338 |
+
def __init__(self, model, extra_args=None, eps_callback=None, info_callback=None):
|
339 |
+
super().__init__()
|
340 |
+
self.model = model
|
341 |
+
self.extra_args = {} if extra_args is None else extra_args
|
342 |
+
self.eps_callback = eps_callback
|
343 |
+
self.info_callback = info_callback
|
344 |
+
|
345 |
+
def t(self, sigma):
|
346 |
+
return -sigma.log()
|
347 |
+
|
348 |
+
def sigma(self, t):
|
349 |
+
return t.neg().exp()
|
350 |
+
|
351 |
+
def eps(self, eps_cache, key, x, t, *args, **kwargs):
|
352 |
+
if key in eps_cache:
|
353 |
+
return eps_cache[key], eps_cache
|
354 |
+
sigma = self.sigma(t) * x.new_ones([x.shape[0]])
|
355 |
+
eps = (x - self.model(x, sigma, *args, **self.extra_args, **kwargs)) / self.sigma(t)
|
356 |
+
if self.eps_callback is not None:
|
357 |
+
self.eps_callback()
|
358 |
+
return eps, {key: eps, **eps_cache}
|
359 |
+
|
360 |
+
def dpm_solver_1_step(self, x, t, t_next, eps_cache=None):
|
361 |
+
eps_cache = {} if eps_cache is None else eps_cache
|
362 |
+
h = t_next - t
|
363 |
+
eps, eps_cache = self.eps(eps_cache, 'eps', x, t)
|
364 |
+
x_1 = x - self.sigma(t_next) * h.expm1() * eps
|
365 |
+
return x_1, eps_cache
|
366 |
+
|
367 |
+
def dpm_solver_2_step(self, x, t, t_next, r1=1 / 2, eps_cache=None):
|
368 |
+
eps_cache = {} if eps_cache is None else eps_cache
|
369 |
+
h = t_next - t
|
370 |
+
eps, eps_cache = self.eps(eps_cache, 'eps', x, t)
|
371 |
+
s1 = t + r1 * h
|
372 |
+
u1 = x - self.sigma(s1) * (r1 * h).expm1() * eps
|
373 |
+
eps_r1, eps_cache = self.eps(eps_cache, 'eps_r1', u1, s1)
|
374 |
+
x_2 = x - self.sigma(t_next) * h.expm1() * eps - self.sigma(t_next) / (2 * r1) * h.expm1() * (eps_r1 - eps)
|
375 |
+
return x_2, eps_cache
|
376 |
+
|
377 |
+
def dpm_solver_3_step(self, x, t, t_next, r1=1 / 3, r2=2 / 3, eps_cache=None):
|
378 |
+
eps_cache = {} if eps_cache is None else eps_cache
|
379 |
+
h = t_next - t
|
380 |
+
eps, eps_cache = self.eps(eps_cache, 'eps', x, t)
|
381 |
+
s1 = t + r1 * h
|
382 |
+
s2 = t + r2 * h
|
383 |
+
u1 = x - self.sigma(s1) * (r1 * h).expm1() * eps
|
384 |
+
eps_r1, eps_cache = self.eps(eps_cache, 'eps_r1', u1, s1)
|
385 |
+
u2 = x - self.sigma(s2) * (r2 * h).expm1() * eps - self.sigma(s2) * (r2 / r1) * ((r2 * h).expm1() / (r2 * h) - 1) * (eps_r1 - eps)
|
386 |
+
eps_r2, eps_cache = self.eps(eps_cache, 'eps_r2', u2, s2)
|
387 |
+
x_3 = x - self.sigma(t_next) * h.expm1() * eps - self.sigma(t_next) / r2 * (h.expm1() / h - 1) * (eps_r2 - eps)
|
388 |
+
return x_3, eps_cache
|
389 |
+
|
390 |
+
def dpm_solver_fast(self, x, t_start, t_end, nfe, eta=0., s_noise=1., noise_sampler=None):
|
391 |
+
noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler
|
392 |
+
if not t_end > t_start and eta:
|
393 |
+
raise ValueError('eta must be 0 for reverse sampling')
|
394 |
+
|
395 |
+
m = math.floor(nfe / 3) + 1
|
396 |
+
ts = torch.linspace(t_start, t_end, m + 1, device=x.device)
|
397 |
+
|
398 |
+
if nfe % 3 == 0:
|
399 |
+
orders = [3] * (m - 2) + [2, 1]
|
400 |
+
else:
|
401 |
+
orders = [3] * (m - 1) + [nfe % 3]
|
402 |
+
|
403 |
+
for i in range(len(orders)):
|
404 |
+
eps_cache = {}
|
405 |
+
t, t_next = ts[i], ts[i + 1]
|
406 |
+
if eta:
|
407 |
+
sd, su = get_ancestral_step(self.sigma(t), self.sigma(t_next), eta)
|
408 |
+
t_next_ = torch.minimum(t_end, self.t(sd))
|
409 |
+
su = (self.sigma(t_next) ** 2 - self.sigma(t_next_) ** 2) ** 0.5
|
410 |
+
else:
|
411 |
+
t_next_, su = t_next, 0.
|
412 |
+
|
413 |
+
eps, eps_cache = self.eps(eps_cache, 'eps', x, t)
|
414 |
+
denoised = x - self.sigma(t) * eps
|
415 |
+
if self.info_callback is not None:
|
416 |
+
self.info_callback({'x': x, 'i': i, 't': ts[i], 't_up': t, 'denoised': denoised})
|
417 |
+
|
418 |
+
if orders[i] == 1:
|
419 |
+
x, eps_cache = self.dpm_solver_1_step(x, t, t_next_, eps_cache=eps_cache)
|
420 |
+
elif orders[i] == 2:
|
421 |
+
x, eps_cache = self.dpm_solver_2_step(x, t, t_next_, eps_cache=eps_cache)
|
422 |
+
else:
|
423 |
+
x, eps_cache = self.dpm_solver_3_step(x, t, t_next_, eps_cache=eps_cache)
|
424 |
+
|
425 |
+
x = x + su * s_noise * noise_sampler(self.sigma(t), self.sigma(t_next))
|
426 |
+
|
427 |
+
return x
|
428 |
+
|
429 |
+
def dpm_solver_adaptive(self, x, t_start, t_end, order=3, rtol=0.05, atol=0.0078, h_init=0.05, pcoeff=0., icoeff=1., dcoeff=0., accept_safety=0.81, eta=0., s_noise=1., noise_sampler=None):
|
430 |
+
noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler
|
431 |
+
if order not in {2, 3}:
|
432 |
+
raise ValueError('order should be 2 or 3')
|
433 |
+
forward = t_end > t_start
|
434 |
+
if not forward and eta:
|
435 |
+
raise ValueError('eta must be 0 for reverse sampling')
|
436 |
+
h_init = abs(h_init) * (1 if forward else -1)
|
437 |
+
atol = torch.tensor(atol)
|
438 |
+
rtol = torch.tensor(rtol)
|
439 |
+
s = t_start
|
440 |
+
x_prev = x
|
441 |
+
accept = True
|
442 |
+
pid = PIDStepSizeController(h_init, pcoeff, icoeff, dcoeff, 1.5 if eta else order, accept_safety)
|
443 |
+
info = {'steps': 0, 'nfe': 0, 'n_accept': 0, 'n_reject': 0}
|
444 |
+
|
445 |
+
while s < t_end - 1e-5 if forward else s > t_end + 1e-5:
|
446 |
+
eps_cache = {}
|
447 |
+
t = torch.minimum(t_end, s + pid.h) if forward else torch.maximum(t_end, s + pid.h)
|
448 |
+
if eta:
|
449 |
+
sd, su = get_ancestral_step(self.sigma(s), self.sigma(t), eta)
|
450 |
+
t_ = torch.minimum(t_end, self.t(sd))
|
451 |
+
su = (self.sigma(t) ** 2 - self.sigma(t_) ** 2) ** 0.5
|
452 |
+
else:
|
453 |
+
t_, su = t, 0.
|
454 |
+
|
455 |
+
eps, eps_cache = self.eps(eps_cache, 'eps', x, s)
|
456 |
+
denoised = x - self.sigma(s) * eps
|
457 |
+
|
458 |
+
if order == 2:
|
459 |
+
x_low, eps_cache = self.dpm_solver_1_step(x, s, t_, eps_cache=eps_cache)
|
460 |
+
x_high, eps_cache = self.dpm_solver_2_step(x, s, t_, eps_cache=eps_cache)
|
461 |
+
else:
|
462 |
+
x_low, eps_cache = self.dpm_solver_2_step(x, s, t_, r1=1 / 3, eps_cache=eps_cache)
|
463 |
+
x_high, eps_cache = self.dpm_solver_3_step(x, s, t_, eps_cache=eps_cache)
|
464 |
+
delta = torch.maximum(atol, rtol * torch.maximum(x_low.abs(), x_prev.abs()))
|
465 |
+
error = torch.linalg.norm((x_low - x_high) / delta) / x.numel() ** 0.5
|
466 |
+
accept = pid.propose_step(error)
|
467 |
+
if accept:
|
468 |
+
x_prev = x_low
|
469 |
+
x = x_high + su * s_noise * noise_sampler(self.sigma(s), self.sigma(t))
|
470 |
+
s = t
|
471 |
+
info['n_accept'] += 1
|
472 |
+
else:
|
473 |
+
info['n_reject'] += 1
|
474 |
+
info['nfe'] += order
|
475 |
+
info['steps'] += 1
|
476 |
+
|
477 |
+
if self.info_callback is not None:
|
478 |
+
self.info_callback({'x': x, 'i': info['steps'] - 1, 't': s, 't_up': s, 'denoised': denoised, 'error': error, 'h': pid.h, **info})
|
479 |
+
|
480 |
+
return x, info
|
481 |
+
|
482 |
+
|
483 |
+
@torch.no_grad()
|
484 |
+
def sample_dpm_fast(model, x, sigma_min, sigma_max, n, extra_args=None, callback=None, disable=None, eta=0., s_noise=1., noise_sampler=None):
|
485 |
+
"""DPM-Solver-Fast (fixed step size). See https://arxiv.org/abs/2206.00927."""
|
486 |
+
if sigma_min <= 0 or sigma_max <= 0:
|
487 |
+
raise ValueError('sigma_min and sigma_max must not be 0')
|
488 |
+
with tqdm(total=n, disable=disable) as pbar:
|
489 |
+
dpm_solver = DPMSolver(model, extra_args, eps_callback=pbar.update)
|
490 |
+
if callback is not None:
|
491 |
+
dpm_solver.info_callback = lambda info: callback({'sigma': dpm_solver.sigma(info['t']), 'sigma_hat': dpm_solver.sigma(info['t_up']), **info})
|
492 |
+
return dpm_solver.dpm_solver_fast(x, dpm_solver.t(torch.tensor(sigma_max)), dpm_solver.t(torch.tensor(sigma_min)), n, eta, s_noise, noise_sampler)
|
493 |
+
|
494 |
+
|
495 |
+
@torch.no_grad()
|
496 |
+
def sample_dpm_adaptive(model, x, sigma_min, sigma_max, extra_args=None, callback=None, disable=None, order=3, rtol=0.05, atol=0.0078, h_init=0.05, pcoeff=0., icoeff=1., dcoeff=0., accept_safety=0.81, eta=0., s_noise=1., noise_sampler=None, return_info=False):
|
497 |
+
"""DPM-Solver-12 and 23 (adaptive step size). See https://arxiv.org/abs/2206.00927."""
|
498 |
+
if sigma_min <= 0 or sigma_max <= 0:
|
499 |
+
raise ValueError('sigma_min and sigma_max must not be 0')
|
500 |
+
with tqdm(disable=disable) as pbar:
|
501 |
+
dpm_solver = DPMSolver(model, extra_args, eps_callback=pbar.update)
|
502 |
+
if callback is not None:
|
503 |
+
dpm_solver.info_callback = lambda info: callback({'sigma': dpm_solver.sigma(info['t']), 'sigma_hat': dpm_solver.sigma(info['t_up']), **info})
|
504 |
+
x, info = dpm_solver.dpm_solver_adaptive(x, dpm_solver.t(torch.tensor(sigma_max)), dpm_solver.t(torch.tensor(sigma_min)), order, rtol, atol, h_init, pcoeff, icoeff, dcoeff, accept_safety, eta, s_noise, noise_sampler)
|
505 |
+
if return_info:
|
506 |
+
return x, info
|
507 |
+
return x
|
508 |
+
|
509 |
+
|
510 |
+
@torch.no_grad()
|
511 |
+
def sample_dpmpp_2s_ancestral(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None):
|
512 |
+
"""Ancestral sampling with DPM-Solver++(2S) second-order steps."""
|
513 |
+
extra_args = {} if extra_args is None else extra_args
|
514 |
+
noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler
|
515 |
+
s_in = x.new_ones([x.shape[0]])
|
516 |
+
sigma_fn = lambda t: t.neg().exp()
|
517 |
+
t_fn = lambda sigma: sigma.log().neg()
|
518 |
+
|
519 |
+
for i in trange(len(sigmas) - 1, disable=disable):
|
520 |
+
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
521 |
+
sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1], eta=eta)
|
522 |
+
if callback is not None:
|
523 |
+
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
524 |
+
if sigma_down == 0:
|
525 |
+
# Euler method
|
526 |
+
d = to_d(x, sigmas[i], denoised)
|
527 |
+
dt = sigma_down - sigmas[i]
|
528 |
+
x = x + d * dt
|
529 |
+
else:
|
530 |
+
# DPM-Solver++(2S)
|
531 |
+
t, t_next = t_fn(sigmas[i]), t_fn(sigma_down)
|
532 |
+
r = 1 / 2
|
533 |
+
h = t_next - t
|
534 |
+
s = t + r * h
|
535 |
+
x_2 = (sigma_fn(s) / sigma_fn(t)) * x - (-h * r).expm1() * denoised
|
536 |
+
denoised_2 = model(x_2, sigma_fn(s) * s_in, **extra_args)
|
537 |
+
x = (sigma_fn(t_next) / sigma_fn(t)) * x - (-h).expm1() * denoised_2
|
538 |
+
# Noise addition
|
539 |
+
if sigmas[i + 1] > 0:
|
540 |
+
x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * sigma_up
|
541 |
+
return x
|
542 |
+
|
543 |
+
|
544 |
+
@torch.no_grad()
|
545 |
+
def sample_dpmpp_sde(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None, r=1 / 2):
|
546 |
+
"""DPM-Solver++ (stochastic)."""
|
547 |
+
if len(sigmas) <= 1:
|
548 |
+
return x
|
549 |
+
|
550 |
+
sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
|
551 |
+
seed = extra_args.get("seed", None)
|
552 |
+
noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=seed, cpu=True) if noise_sampler is None else noise_sampler
|
553 |
+
extra_args = {} if extra_args is None else extra_args
|
554 |
+
s_in = x.new_ones([x.shape[0]])
|
555 |
+
sigma_fn = lambda t: t.neg().exp()
|
556 |
+
t_fn = lambda sigma: sigma.log().neg()
|
557 |
+
|
558 |
+
for i in trange(len(sigmas) - 1, disable=disable):
|
559 |
+
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
560 |
+
if callback is not None:
|
561 |
+
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
562 |
+
if sigmas[i + 1] == 0:
|
563 |
+
# Euler method
|
564 |
+
d = to_d(x, sigmas[i], denoised)
|
565 |
+
dt = sigmas[i + 1] - sigmas[i]
|
566 |
+
x = x + d * dt
|
567 |
+
else:
|
568 |
+
# DPM-Solver++
|
569 |
+
t, t_next = t_fn(sigmas[i]), t_fn(sigmas[i + 1])
|
570 |
+
h = t_next - t
|
571 |
+
s = t + h * r
|
572 |
+
fac = 1 / (2 * r)
|
573 |
+
|
574 |
+
# Step 1
|
575 |
+
sd, su = get_ancestral_step(sigma_fn(t), sigma_fn(s), eta)
|
576 |
+
s_ = t_fn(sd)
|
577 |
+
x_2 = (sigma_fn(s_) / sigma_fn(t)) * x - (t - s_).expm1() * denoised
|
578 |
+
x_2 = x_2 + noise_sampler(sigma_fn(t), sigma_fn(s)) * s_noise * su
|
579 |
+
denoised_2 = model(x_2, sigma_fn(s) * s_in, **extra_args)
|
580 |
+
|
581 |
+
# Step 2
|
582 |
+
sd, su = get_ancestral_step(sigma_fn(t), sigma_fn(t_next), eta)
|
583 |
+
t_next_ = t_fn(sd)
|
584 |
+
denoised_d = (1 - fac) * denoised + fac * denoised_2
|
585 |
+
x = (sigma_fn(t_next_) / sigma_fn(t)) * x - (t - t_next_).expm1() * denoised_d
|
586 |
+
x = x + noise_sampler(sigma_fn(t), sigma_fn(t_next)) * s_noise * su
|
587 |
+
return x
|
588 |
+
|
589 |
+
|
590 |
+
@torch.no_grad()
|
591 |
+
def sample_dpmpp_2m(model, x, sigmas, extra_args=None, callback=None, disable=None):
|
592 |
+
"""DPM-Solver++(2M)."""
|
593 |
+
extra_args = {} if extra_args is None else extra_args
|
594 |
+
s_in = x.new_ones([x.shape[0]])
|
595 |
+
sigma_fn = lambda t: t.neg().exp()
|
596 |
+
t_fn = lambda sigma: sigma.log().neg()
|
597 |
+
old_denoised = None
|
598 |
+
|
599 |
+
for i in trange(len(sigmas) - 1, disable=disable):
|
600 |
+
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
601 |
+
if callback is not None:
|
602 |
+
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
603 |
+
t, t_next = t_fn(sigmas[i]), t_fn(sigmas[i + 1])
|
604 |
+
h = t_next - t
|
605 |
+
if old_denoised is None or sigmas[i + 1] == 0:
|
606 |
+
x = (sigma_fn(t_next) / sigma_fn(t)) * x - (-h).expm1() * denoised
|
607 |
+
else:
|
608 |
+
h_last = t - t_fn(sigmas[i - 1])
|
609 |
+
r = h_last / h
|
610 |
+
denoised_d = (1 + 1 / (2 * r)) * denoised - (1 / (2 * r)) * old_denoised
|
611 |
+
x = (sigma_fn(t_next) / sigma_fn(t)) * x - (-h).expm1() * denoised_d
|
612 |
+
old_denoised = denoised
|
613 |
+
return x
|
614 |
+
|
615 |
+
@torch.no_grad()
|
616 |
+
def sample_dpmpp_2m_sde(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None, solver_type='midpoint'):
|
617 |
+
"""DPM-Solver++(2M) SDE."""
|
618 |
+
if len(sigmas) <= 1:
|
619 |
+
return x
|
620 |
+
|
621 |
+
if solver_type not in {'heun', 'midpoint'}:
|
622 |
+
raise ValueError('solver_type must be \'heun\' or \'midpoint\'')
|
623 |
+
|
624 |
+
seed = extra_args.get("seed", None)
|
625 |
+
sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
|
626 |
+
noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=seed, cpu=True) if noise_sampler is None else noise_sampler
|
627 |
+
extra_args = {} if extra_args is None else extra_args
|
628 |
+
s_in = x.new_ones([x.shape[0]])
|
629 |
+
|
630 |
+
old_denoised = None
|
631 |
+
h_last = None
|
632 |
+
h = None
|
633 |
+
|
634 |
+
for i in trange(len(sigmas) - 1, disable=disable):
|
635 |
+
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
636 |
+
if callback is not None:
|
637 |
+
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
638 |
+
if sigmas[i + 1] == 0:
|
639 |
+
# Denoising step
|
640 |
+
x = denoised
|
641 |
+
else:
|
642 |
+
# DPM-Solver++(2M) SDE
|
643 |
+
t, s = -sigmas[i].log(), -sigmas[i + 1].log()
|
644 |
+
h = s - t
|
645 |
+
eta_h = eta * h
|
646 |
+
|
647 |
+
x = sigmas[i + 1] / sigmas[i] * (-eta_h).exp() * x + (-h - eta_h).expm1().neg() * denoised
|
648 |
+
|
649 |
+
if old_denoised is not None:
|
650 |
+
r = h_last / h
|
651 |
+
if solver_type == 'heun':
|
652 |
+
x = x + ((-h - eta_h).expm1().neg() / (-h - eta_h) + 1) * (1 / r) * (denoised - old_denoised)
|
653 |
+
elif solver_type == 'midpoint':
|
654 |
+
x = x + 0.5 * (-h - eta_h).expm1().neg() * (1 / r) * (denoised - old_denoised)
|
655 |
+
|
656 |
+
if eta:
|
657 |
+
x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * sigmas[i + 1] * (-2 * eta_h).expm1().neg().sqrt() * s_noise
|
658 |
+
|
659 |
+
old_denoised = denoised
|
660 |
+
h_last = h
|
661 |
+
return x
|
662 |
+
|
663 |
+
@torch.no_grad()
|
664 |
+
def sample_dpmpp_3m_sde(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None):
|
665 |
+
"""DPM-Solver++(3M) SDE."""
|
666 |
+
|
667 |
+
if len(sigmas) <= 1:
|
668 |
+
return x
|
669 |
+
|
670 |
+
seed = extra_args.get("seed", None)
|
671 |
+
sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
|
672 |
+
noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=seed, cpu=True) if noise_sampler is None else noise_sampler
|
673 |
+
extra_args = {} if extra_args is None else extra_args
|
674 |
+
s_in = x.new_ones([x.shape[0]])
|
675 |
+
|
676 |
+
denoised_1, denoised_2 = None, None
|
677 |
+
h, h_1, h_2 = None, None, None
|
678 |
+
|
679 |
+
for i in trange(len(sigmas) - 1, disable=disable):
|
680 |
+
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
681 |
+
if callback is not None:
|
682 |
+
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
683 |
+
if sigmas[i + 1] == 0:
|
684 |
+
# Denoising step
|
685 |
+
x = denoised
|
686 |
+
else:
|
687 |
+
t, s = -sigmas[i].log(), -sigmas[i + 1].log()
|
688 |
+
h = s - t
|
689 |
+
h_eta = h * (eta + 1)
|
690 |
+
|
691 |
+
x = torch.exp(-h_eta) * x + (-h_eta).expm1().neg() * denoised
|
692 |
+
|
693 |
+
if h_2 is not None:
|
694 |
+
r0 = h_1 / h
|
695 |
+
r1 = h_2 / h
|
696 |
+
d1_0 = (denoised - denoised_1) / r0
|
697 |
+
d1_1 = (denoised_1 - denoised_2) / r1
|
698 |
+
d1 = d1_0 + (d1_0 - d1_1) * r0 / (r0 + r1)
|
699 |
+
d2 = (d1_0 - d1_1) / (r0 + r1)
|
700 |
+
phi_2 = h_eta.neg().expm1() / h_eta + 1
|
701 |
+
phi_3 = phi_2 / h_eta - 0.5
|
702 |
+
x = x + phi_2 * d1 - phi_3 * d2
|
703 |
+
elif h_1 is not None:
|
704 |
+
r = h_1 / h
|
705 |
+
d = (denoised - denoised_1) / r
|
706 |
+
phi_2 = h_eta.neg().expm1() / h_eta + 1
|
707 |
+
x = x + phi_2 * d
|
708 |
+
|
709 |
+
if eta:
|
710 |
+
x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * sigmas[i + 1] * (-2 * h * eta).expm1().neg().sqrt() * s_noise
|
711 |
+
|
712 |
+
denoised_1, denoised_2 = denoised, denoised_1
|
713 |
+
h_1, h_2 = h, h_1
|
714 |
+
return x
|
715 |
+
|
716 |
+
@torch.no_grad()
|
717 |
+
def sample_dpmpp_3m_sde_gpu(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None):
|
718 |
+
if len(sigmas) <= 1:
|
719 |
+
return x
|
720 |
+
|
721 |
+
sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
|
722 |
+
noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=extra_args.get("seed", None), cpu=False) if noise_sampler is None else noise_sampler
|
723 |
+
return sample_dpmpp_3m_sde(model, x, sigmas, extra_args=extra_args, callback=callback, disable=disable, eta=eta, s_noise=s_noise, noise_sampler=noise_sampler)
|
724 |
+
|
725 |
+
@torch.no_grad()
|
726 |
+
def sample_dpmpp_2m_sde_gpu(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None, solver_type='midpoint'):
|
727 |
+
if len(sigmas) <= 1:
|
728 |
+
return x
|
729 |
+
|
730 |
+
sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
|
731 |
+
noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=extra_args.get("seed", None), cpu=False) if noise_sampler is None else noise_sampler
|
732 |
+
return sample_dpmpp_2m_sde(model, x, sigmas, extra_args=extra_args, callback=callback, disable=disable, eta=eta, s_noise=s_noise, noise_sampler=noise_sampler, solver_type=solver_type)
|
733 |
+
|
734 |
+
@torch.no_grad()
|
735 |
+
def sample_dpmpp_sde_gpu(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None, r=1 / 2):
|
736 |
+
if len(sigmas) <= 1:
|
737 |
+
return x
|
738 |
+
|
739 |
+
sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
|
740 |
+
noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=extra_args.get("seed", None), cpu=False) if noise_sampler is None else noise_sampler
|
741 |
+
return sample_dpmpp_sde(model, x, sigmas, extra_args=extra_args, callback=callback, disable=disable, eta=eta, s_noise=s_noise, noise_sampler=noise_sampler, r=r)
|
742 |
+
|
743 |
+
|
744 |
+
def DDPMSampler_step(x, sigma, sigma_prev, noise, noise_sampler):
|
745 |
+
alpha_cumprod = 1 / ((sigma * sigma) + 1)
|
746 |
+
alpha_cumprod_prev = 1 / ((sigma_prev * sigma_prev) + 1)
|
747 |
+
alpha = (alpha_cumprod / alpha_cumprod_prev)
|
748 |
+
|
749 |
+
mu = (1.0 / alpha).sqrt() * (x - (1 - alpha) * noise / (1 - alpha_cumprod).sqrt())
|
750 |
+
if sigma_prev > 0:
|
751 |
+
mu += ((1 - alpha) * (1. - alpha_cumprod_prev) / (1. - alpha_cumprod)).sqrt() * noise_sampler(sigma, sigma_prev)
|
752 |
+
return mu
|
753 |
+
|
754 |
+
def generic_step_sampler(model, x, sigmas, extra_args=None, callback=None, disable=None, noise_sampler=None, step_function=None):
|
755 |
+
extra_args = {} if extra_args is None else extra_args
|
756 |
+
noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler
|
757 |
+
s_in = x.new_ones([x.shape[0]])
|
758 |
+
|
759 |
+
for i in trange(len(sigmas) - 1, disable=disable):
|
760 |
+
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
761 |
+
if callback is not None:
|
762 |
+
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
763 |
+
x = step_function(x / torch.sqrt(1.0 + sigmas[i] ** 2.0), sigmas[i], sigmas[i + 1], (x - denoised) / sigmas[i], noise_sampler)
|
764 |
+
if sigmas[i + 1] != 0:
|
765 |
+
x *= torch.sqrt(1.0 + sigmas[i + 1] ** 2.0)
|
766 |
+
return x
|
767 |
+
|
768 |
+
|
769 |
+
@torch.no_grad()
|
770 |
+
def sample_ddpm(model, x, sigmas, extra_args=None, callback=None, disable=None, noise_sampler=None):
|
771 |
+
return generic_step_sampler(model, x, sigmas, extra_args, callback, disable, noise_sampler, DDPMSampler_step)
|
772 |
+
|
773 |
+
@torch.no_grad()
|
774 |
+
def sample_lcm(model, x, sigmas, extra_args=None, callback=None, disable=None, noise_sampler=None):
|
775 |
+
extra_args = {} if extra_args is None else extra_args
|
776 |
+
noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler
|
777 |
+
s_in = x.new_ones([x.shape[0]])
|
778 |
+
for i in trange(len(sigmas) - 1, disable=disable):
|
779 |
+
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
780 |
+
if callback is not None:
|
781 |
+
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
782 |
+
|
783 |
+
x = denoised
|
784 |
+
if sigmas[i + 1] > 0:
|
785 |
+
x = model.inner_model.inner_model.model_sampling.noise_scaling(sigmas[i + 1], noise_sampler(sigmas[i], sigmas[i + 1]), x)
|
786 |
+
return x
|
787 |
+
|
788 |
+
|
789 |
+
|
790 |
+
@torch.no_grad()
|
791 |
+
def sample_heunpp2(model, x, sigmas, extra_args=None, callback=None, disable=None, s_churn=0., s_tmin=0., s_tmax=float('inf'), s_noise=1.):
|
792 |
+
# From MIT licensed: https://github.com/Carzit/sd-webui-samplers-scheduler/
|
793 |
+
extra_args = {} if extra_args is None else extra_args
|
794 |
+
s_in = x.new_ones([x.shape[0]])
|
795 |
+
s_end = sigmas[-1]
|
796 |
+
for i in trange(len(sigmas) - 1, disable=disable):
|
797 |
+
gamma = min(s_churn / (len(sigmas) - 1), 2 ** 0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0.
|
798 |
+
eps = torch.randn_like(x) * s_noise
|
799 |
+
sigma_hat = sigmas[i] * (gamma + 1)
|
800 |
+
if gamma > 0:
|
801 |
+
x = x + eps * (sigma_hat ** 2 - sigmas[i] ** 2) ** 0.5
|
802 |
+
denoised = model(x, sigma_hat * s_in, **extra_args)
|
803 |
+
d = to_d(x, sigma_hat, denoised)
|
804 |
+
if callback is not None:
|
805 |
+
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigma_hat, 'denoised': denoised})
|
806 |
+
dt = sigmas[i + 1] - sigma_hat
|
807 |
+
if sigmas[i + 1] == s_end:
|
808 |
+
# Euler method
|
809 |
+
x = x + d * dt
|
810 |
+
elif sigmas[i + 2] == s_end:
|
811 |
+
|
812 |
+
# Heun's method
|
813 |
+
x_2 = x + d * dt
|
814 |
+
denoised_2 = model(x_2, sigmas[i + 1] * s_in, **extra_args)
|
815 |
+
d_2 = to_d(x_2, sigmas[i + 1], denoised_2)
|
816 |
+
|
817 |
+
w = 2 * sigmas[0]
|
818 |
+
w2 = sigmas[i+1]/w
|
819 |
+
w1 = 1 - w2
|
820 |
+
|
821 |
+
d_prime = d * w1 + d_2 * w2
|
822 |
+
|
823 |
+
|
824 |
+
x = x + d_prime * dt
|
825 |
+
|
826 |
+
else:
|
827 |
+
# Heun++
|
828 |
+
x_2 = x + d * dt
|
829 |
+
denoised_2 = model(x_2, sigmas[i + 1] * s_in, **extra_args)
|
830 |
+
d_2 = to_d(x_2, sigmas[i + 1], denoised_2)
|
831 |
+
dt_2 = sigmas[i + 2] - sigmas[i + 1]
|
832 |
+
|
833 |
+
x_3 = x_2 + d_2 * dt_2
|
834 |
+
denoised_3 = model(x_3, sigmas[i + 2] * s_in, **extra_args)
|
835 |
+
d_3 = to_d(x_3, sigmas[i + 2], denoised_3)
|
836 |
+
|
837 |
+
w = 3 * sigmas[0]
|
838 |
+
w2 = sigmas[i + 1] / w
|
839 |
+
w3 = sigmas[i + 2] / w
|
840 |
+
w1 = 1 - w2 - w3
|
841 |
+
|
842 |
+
d_prime = w1 * d + w2 * d_2 + w3 * d_3
|
843 |
+
x = x + d_prime * dt
|
844 |
+
return x
|
845 |
+
|
846 |
+
|
847 |
+
#From https://github.com/zju-pi/diff-sampler/blob/main/diff-solvers-main/solvers.py
|
848 |
+
#under Apache 2 license
|
849 |
+
def sample_ipndm(model, x, sigmas, extra_args=None, callback=None, disable=None, max_order=4):
|
850 |
+
extra_args = {} if extra_args is None else extra_args
|
851 |
+
s_in = x.new_ones([x.shape[0]])
|
852 |
+
|
853 |
+
x_next = x
|
854 |
+
|
855 |
+
buffer_model = []
|
856 |
+
for i in trange(len(sigmas) - 1, disable=disable):
|
857 |
+
t_cur = sigmas[i]
|
858 |
+
t_next = sigmas[i + 1]
|
859 |
+
|
860 |
+
x_cur = x_next
|
861 |
+
|
862 |
+
denoised = model(x_cur, t_cur * s_in, **extra_args)
|
863 |
+
if callback is not None:
|
864 |
+
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
865 |
+
|
866 |
+
d_cur = (x_cur - denoised) / t_cur
|
867 |
+
|
868 |
+
order = min(max_order, i+1)
|
869 |
+
if order == 1: # First Euler step.
|
870 |
+
x_next = x_cur + (t_next - t_cur) * d_cur
|
871 |
+
elif order == 2: # Use one history point.
|
872 |
+
x_next = x_cur + (t_next - t_cur) * (3 * d_cur - buffer_model[-1]) / 2
|
873 |
+
elif order == 3: # Use two history points.
|
874 |
+
x_next = x_cur + (t_next - t_cur) * (23 * d_cur - 16 * buffer_model[-1] + 5 * buffer_model[-2]) / 12
|
875 |
+
elif order == 4: # Use three history points.
|
876 |
+
x_next = x_cur + (t_next - t_cur) * (55 * d_cur - 59 * buffer_model[-1] + 37 * buffer_model[-2] - 9 * buffer_model[-3]) / 24
|
877 |
+
|
878 |
+
if len(buffer_model) == max_order - 1:
|
879 |
+
for k in range(max_order - 2):
|
880 |
+
buffer_model[k] = buffer_model[k+1]
|
881 |
+
buffer_model[-1] = d_cur
|
882 |
+
else:
|
883 |
+
buffer_model.append(d_cur)
|
884 |
+
|
885 |
+
return x_next
|
886 |
+
|
887 |
+
#From https://github.com/zju-pi/diff-sampler/blob/main/diff-solvers-main/solvers.py
|
888 |
+
#under Apache 2 license
|
889 |
+
def sample_ipndm_v(model, x, sigmas, extra_args=None, callback=None, disable=None, max_order=4):
|
890 |
+
extra_args = {} if extra_args is None else extra_args
|
891 |
+
s_in = x.new_ones([x.shape[0]])
|
892 |
+
|
893 |
+
x_next = x
|
894 |
+
t_steps = sigmas
|
895 |
+
|
896 |
+
buffer_model = []
|
897 |
+
for i in trange(len(sigmas) - 1, disable=disable):
|
898 |
+
t_cur = sigmas[i]
|
899 |
+
t_next = sigmas[i + 1]
|
900 |
+
|
901 |
+
x_cur = x_next
|
902 |
+
|
903 |
+
denoised = model(x_cur, t_cur * s_in, **extra_args)
|
904 |
+
if callback is not None:
|
905 |
+
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
906 |
+
|
907 |
+
d_cur = (x_cur - denoised) / t_cur
|
908 |
+
|
909 |
+
order = min(max_order, i+1)
|
910 |
+
if order == 1: # First Euler step.
|
911 |
+
x_next = x_cur + (t_next - t_cur) * d_cur
|
912 |
+
elif order == 2: # Use one history point.
|
913 |
+
h_n = (t_next - t_cur)
|
914 |
+
h_n_1 = (t_cur - t_steps[i-1])
|
915 |
+
coeff1 = (2 + (h_n / h_n_1)) / 2
|
916 |
+
coeff2 = -(h_n / h_n_1) / 2
|
917 |
+
x_next = x_cur + (t_next - t_cur) * (coeff1 * d_cur + coeff2 * buffer_model[-1])
|
918 |
+
elif order == 3: # Use two history points.
|
919 |
+
h_n = (t_next - t_cur)
|
920 |
+
h_n_1 = (t_cur - t_steps[i-1])
|
921 |
+
h_n_2 = (t_steps[i-1] - t_steps[i-2])
|
922 |
+
temp = (1 - h_n / (3 * (h_n + h_n_1)) * (h_n * (h_n + h_n_1)) / (h_n_1 * (h_n_1 + h_n_2))) / 2
|
923 |
+
coeff1 = (2 + (h_n / h_n_1)) / 2 + temp
|
924 |
+
coeff2 = -(h_n / h_n_1) / 2 - (1 + h_n_1 / h_n_2) * temp
|
925 |
+
coeff3 = temp * h_n_1 / h_n_2
|
926 |
+
x_next = x_cur + (t_next - t_cur) * (coeff1 * d_cur + coeff2 * buffer_model[-1] + coeff3 * buffer_model[-2])
|
927 |
+
elif order == 4: # Use three history points.
|
928 |
+
h_n = (t_next - t_cur)
|
929 |
+
h_n_1 = (t_cur - t_steps[i-1])
|
930 |
+
h_n_2 = (t_steps[i-1] - t_steps[i-2])
|
931 |
+
h_n_3 = (t_steps[i-2] - t_steps[i-3])
|
932 |
+
temp1 = (1 - h_n / (3 * (h_n + h_n_1)) * (h_n * (h_n + h_n_1)) / (h_n_1 * (h_n_1 + h_n_2))) / 2
|
933 |
+
temp2 = ((1 - h_n / (3 * (h_n + h_n_1))) / 2 + (1 - h_n / (2 * (h_n + h_n_1))) * h_n / (6 * (h_n + h_n_1 + h_n_2))) \
|
934 |
+
* (h_n * (h_n + h_n_1) * (h_n + h_n_1 + h_n_2)) / (h_n_1 * (h_n_1 + h_n_2) * (h_n_1 + h_n_2 + h_n_3))
|
935 |
+
coeff1 = (2 + (h_n / h_n_1)) / 2 + temp1 + temp2
|
936 |
+
coeff2 = -(h_n / h_n_1) / 2 - (1 + h_n_1 / h_n_2) * temp1 - (1 + (h_n_1 / h_n_2) + (h_n_1 * (h_n_1 + h_n_2) / (h_n_2 * (h_n_2 + h_n_3)))) * temp2
|
937 |
+
coeff3 = temp1 * h_n_1 / h_n_2 + ((h_n_1 / h_n_2) + (h_n_1 * (h_n_1 + h_n_2) / (h_n_2 * (h_n_2 + h_n_3))) * (1 + h_n_2 / h_n_3)) * temp2
|
938 |
+
coeff4 = -temp2 * (h_n_1 * (h_n_1 + h_n_2) / (h_n_2 * (h_n_2 + h_n_3))) * h_n_1 / h_n_2
|
939 |
+
x_next = x_cur + (t_next - t_cur) * (coeff1 * d_cur + coeff2 * buffer_model[-1] + coeff3 * buffer_model[-2] + coeff4 * buffer_model[-3])
|
940 |
+
|
941 |
+
if len(buffer_model) == max_order - 1:
|
942 |
+
for k in range(max_order - 2):
|
943 |
+
buffer_model[k] = buffer_model[k+1]
|
944 |
+
buffer_model[-1] = d_cur.detach()
|
945 |
+
else:
|
946 |
+
buffer_model.append(d_cur.detach())
|
947 |
+
|
948 |
+
return x_next
|
949 |
+
|
950 |
+
#From https://github.com/zju-pi/diff-sampler/blob/main/diff-solvers-main/solvers.py
|
951 |
+
#under Apache 2 license
|
952 |
+
@torch.no_grad()
|
953 |
+
def sample_deis(model, x, sigmas, extra_args=None, callback=None, disable=None, max_order=3, deis_mode='tab'):
|
954 |
+
extra_args = {} if extra_args is None else extra_args
|
955 |
+
s_in = x.new_ones([x.shape[0]])
|
956 |
+
|
957 |
+
x_next = x
|
958 |
+
t_steps = sigmas
|
959 |
+
|
960 |
+
coeff_list = deis.get_deis_coeff_list(t_steps, max_order, deis_mode=deis_mode)
|
961 |
+
|
962 |
+
buffer_model = []
|
963 |
+
for i in trange(len(sigmas) - 1, disable=disable):
|
964 |
+
t_cur = sigmas[i]
|
965 |
+
t_next = sigmas[i + 1]
|
966 |
+
|
967 |
+
x_cur = x_next
|
968 |
+
|
969 |
+
denoised = model(x_cur, t_cur * s_in, **extra_args)
|
970 |
+
if callback is not None:
|
971 |
+
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
972 |
+
|
973 |
+
d_cur = (x_cur - denoised) / t_cur
|
974 |
+
|
975 |
+
order = min(max_order, i+1)
|
976 |
+
if t_next <= 0:
|
977 |
+
order = 1
|
978 |
+
|
979 |
+
if order == 1: # First Euler step.
|
980 |
+
x_next = x_cur + (t_next - t_cur) * d_cur
|
981 |
+
elif order == 2: # Use one history point.
|
982 |
+
coeff_cur, coeff_prev1 = coeff_list[i]
|
983 |
+
x_next = x_cur + coeff_cur * d_cur + coeff_prev1 * buffer_model[-1]
|
984 |
+
elif order == 3: # Use two history points.
|
985 |
+
coeff_cur, coeff_prev1, coeff_prev2 = coeff_list[i]
|
986 |
+
x_next = x_cur + coeff_cur * d_cur + coeff_prev1 * buffer_model[-1] + coeff_prev2 * buffer_model[-2]
|
987 |
+
elif order == 4: # Use three history points.
|
988 |
+
coeff_cur, coeff_prev1, coeff_prev2, coeff_prev3 = coeff_list[i]
|
989 |
+
x_next = x_cur + coeff_cur * d_cur + coeff_prev1 * buffer_model[-1] + coeff_prev2 * buffer_model[-2] + coeff_prev3 * buffer_model[-3]
|
990 |
+
|
991 |
+
if len(buffer_model) == max_order - 1:
|
992 |
+
for k in range(max_order - 2):
|
993 |
+
buffer_model[k] = buffer_model[k+1]
|
994 |
+
buffer_model[-1] = d_cur.detach()
|
995 |
+
else:
|
996 |
+
buffer_model.append(d_cur.detach())
|
997 |
+
|
998 |
+
return x_next
|
999 |
+
|
1000 |
+
@torch.no_grad()
|
1001 |
+
def sample_euler_cfg_pp(model, x, sigmas, extra_args=None, callback=None, disable=None):
|
1002 |
+
extra_args = {} if extra_args is None else extra_args
|
1003 |
+
|
1004 |
+
temp = [0]
|
1005 |
+
def post_cfg_function(args):
|
1006 |
+
temp[0] = args["uncond_denoised"]
|
1007 |
+
return args["denoised"]
|
1008 |
+
|
1009 |
+
model_options = extra_args.get("model_options", {}).copy()
|
1010 |
+
extra_args["model_options"] = comfy.model_patcher.set_model_options_post_cfg_function(model_options, post_cfg_function, disable_cfg1_optimization=True)
|
1011 |
+
|
1012 |
+
s_in = x.new_ones([x.shape[0]])
|
1013 |
+
for i in trange(len(sigmas) - 1, disable=disable):
|
1014 |
+
sigma_hat = sigmas[i]
|
1015 |
+
denoised = model(x, sigma_hat * s_in, **extra_args)
|
1016 |
+
d = to_d(x, sigma_hat, temp[0])
|
1017 |
+
if callback is not None:
|
1018 |
+
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigma_hat, 'denoised': denoised})
|
1019 |
+
dt = sigmas[i + 1] - sigma_hat
|
1020 |
+
# Euler method
|
1021 |
+
x = denoised + d * sigmas[i + 1]
|
1022 |
+
return x
|
1023 |
+
|
1024 |
+
@torch.no_grad()
|
1025 |
+
def sample_euler_ancestral_cfg_pp(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None):
|
1026 |
+
"""Ancestral sampling with Euler method steps."""
|
1027 |
+
extra_args = {} if extra_args is None else extra_args
|
1028 |
+
noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler
|
1029 |
+
|
1030 |
+
temp = [0]
|
1031 |
+
def post_cfg_function(args):
|
1032 |
+
temp[0] = args["uncond_denoised"]
|
1033 |
+
return args["denoised"]
|
1034 |
+
|
1035 |
+
model_options = extra_args.get("model_options", {}).copy()
|
1036 |
+
extra_args["model_options"] = comfy.model_patcher.set_model_options_post_cfg_function(model_options, post_cfg_function, disable_cfg1_optimization=True)
|
1037 |
+
|
1038 |
+
s_in = x.new_ones([x.shape[0]])
|
1039 |
+
for i in trange(len(sigmas) - 1, disable=disable):
|
1040 |
+
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
1041 |
+
sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1], eta=eta)
|
1042 |
+
if callback is not None:
|
1043 |
+
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
1044 |
+
d = to_d(x, sigmas[i], temp[0])
|
1045 |
+
# Euler method
|
1046 |
+
dt = sigma_down - sigmas[i]
|
1047 |
+
x = denoised + d * sigma_down
|
1048 |
+
if sigmas[i + 1] > 0:
|
1049 |
+
x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * sigma_up
|
1050 |
+
return x
|