Compare commits
280 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bfee03d8d9 | ||
|
|
0af28699c4 | ||
|
|
29be1da7cf | ||
|
|
10b5ca2541 | ||
|
|
e48533bdcd | ||
|
|
b9705c58f6 | ||
|
|
ce273aef88 | ||
|
|
95bcea72b1 | ||
|
|
72139b000c | ||
|
|
ef35383b4a | ||
|
|
b59deaa382 | ||
|
|
d23c694a84 | ||
|
|
e9e8047978 | ||
|
|
cc1c0829d5 | ||
|
|
c8a5322d1f | ||
|
|
ca0308b60d | ||
|
|
6e6cc2922d | ||
|
|
5166a723c2 | ||
|
|
7155b993ca | ||
|
|
1546fa8b89 | ||
|
|
6287c73d98 | ||
|
|
2b7ddcbb5c | ||
|
|
e3a8dc6e23 | ||
|
|
ca8dc2bde2 | ||
|
|
900419e85e | ||
|
|
a252bbcf16 | ||
|
|
b458e42096 | ||
|
|
beb6e76135 | ||
|
|
056d4d0f91 | ||
|
|
a0c89fae12 | ||
|
|
5e5b60b5b1 | ||
|
|
437c348926 | ||
|
|
50229a05c1 | ||
|
|
434ca2169f | ||
|
|
0f09d98814 | ||
|
|
79bdb78619 | ||
|
|
2ecb869f31 | ||
|
|
a844834193 | ||
|
|
d508d8132f | ||
|
|
88f395091b | ||
|
|
54c89503eb | ||
|
|
16caff3d14 | ||
|
|
9d4c88912d | ||
|
|
bde779a526 | ||
|
|
2a7fb1be24 | ||
|
|
cc5f773519 | ||
|
|
1c6e4b698b | ||
|
|
ad0ce480f9 | ||
|
|
df12dde12e | ||
|
|
19473b1a26 | ||
|
|
26c325296e | ||
|
|
3a99824638 | ||
|
|
bab918f049 | ||
|
|
ed594d7ba6 | ||
|
|
eacb14e115 | ||
|
|
9211febbfc | ||
|
|
18819723c1 | ||
|
|
3f18a09c86 | ||
|
|
8283774b86 | ||
|
|
6ebef20db3 | ||
|
|
167dbc6411 | ||
|
|
58985e6b37 | ||
|
|
ab1e0fa9bf | ||
|
|
85abbbb8fa | ||
|
|
539bc5035d | ||
|
|
4080e25805 | ||
|
|
846fdc3341 | ||
|
|
638ee43bf1 | ||
|
|
95ddac3117 | ||
|
|
b713542cd8 | ||
|
|
b4f3c1971b | ||
|
|
1da05297ea | ||
|
|
f537e5a519 | ||
|
|
4ce60f2176 | ||
|
|
c4afdb7895 | ||
|
|
64179c3221 | ||
|
|
591470d86d | ||
|
|
a5436a3ac0 | ||
|
|
0a271938d8 | ||
|
|
33c8fe1221 | ||
|
|
6e4fc5e1a8 | ||
|
|
4eb949625c | ||
|
|
5a8dd0c549 | ||
|
|
9d5becb4de | ||
|
|
71072f5620 | ||
|
|
43c9e3b5ce | ||
|
|
ae51178629 | ||
|
|
07659efd88 | ||
|
|
9e42470a2d | ||
|
|
7a2aca6fed | ||
|
|
a18e54ecd7 | ||
|
|
7071321792 | ||
|
|
4ff1fabc86 | ||
|
|
4573195894 | ||
|
|
db19c46d6d | ||
|
|
1466daeafc | ||
|
|
dd1641ecc4 | ||
|
|
7dae6bb3b5 | ||
|
|
2e1b61e590 | ||
|
|
f293dbbf97 | ||
|
|
bf08a5b75e | ||
|
|
48ce0379bc | ||
|
|
d235aa068d | ||
|
|
ce57a6c6db | ||
|
|
d70632a7cf | ||
|
|
4333ecc43f | ||
|
|
a56125b0a8 | ||
|
|
23f03d4796 | ||
|
|
06ab10a1be | ||
|
|
6ee4012c0a | ||
|
|
46988af636 | ||
|
|
18ec22bffe | ||
|
|
1142201a3a | ||
|
|
d81e353d89 | ||
|
|
fa8be06613 | ||
|
|
b50d978e1b | ||
|
|
2616c20687 | ||
|
|
69f9564a6d | ||
|
|
4777898a0c | ||
|
|
90441294db | ||
|
|
3cdae09639 | ||
|
|
237f80681a | ||
|
|
30dd8af08c | ||
|
|
3d039591fe | ||
|
|
9c5038c766 | ||
|
|
f5bf7799f4 | ||
|
|
11dcc6c96c | ||
|
|
bc5589b249 | ||
|
|
30c8d742b3 | ||
|
|
eca4d296f5 | ||
|
|
13fd466c18 | ||
|
|
8316773caa | ||
|
|
b7f45e67dc | ||
|
|
02ab75b86a | ||
|
|
f6e476d7a8 | ||
|
|
b531b0bbef | ||
|
|
e2b19900ec | ||
|
|
e11753ff84 | ||
|
|
3732cf2f97 | ||
|
|
2f1e2c492f | ||
|
|
860534399b | ||
|
|
4d46f8c25c | ||
|
|
5ddd5d29e5 | ||
|
|
440fff64a2 | ||
|
|
d2246df160 | ||
|
|
6a854fcb38 | ||
|
|
ee023f4fbf | ||
|
|
c04c4b95de | ||
|
|
15bb49e761 | ||
|
|
6e71d97478 | ||
|
|
998327c744 | ||
|
|
7583351760 | ||
|
|
82e2e25325 | ||
|
|
44b647a83e | ||
|
|
ce21e7afe4 | ||
|
|
ac94f38d9a | ||
|
|
5a7e755528 | ||
|
|
bd0878754c | ||
|
|
371687a1da | ||
|
|
e9459b6c4a | ||
|
|
ee565b337c | ||
|
|
d6f2e5bdd9 | ||
|
|
dca0a1d5d8 | ||
|
|
4ec1015162 | ||
|
|
2ba0277b52 | ||
|
|
fb2e271668 | ||
|
|
d2af6d1b44 | ||
|
|
54edd29725 | ||
|
|
8c8f948666 | ||
|
|
8059533eaf | ||
|
|
200f2b69ed | ||
|
|
ac4a8820a5 | ||
|
|
472a510151 | ||
|
|
e8f51579cc | ||
|
|
658da35cdc | ||
|
|
542611cce4 | ||
|
|
c06769c1fa | ||
|
|
c3c88ca8b4 | ||
|
|
6b3f7039b6 | ||
|
|
6b8458eb9f | ||
|
|
0bc7867ccd | ||
|
|
d69a7944c9 | ||
|
|
eb6f2df826 | ||
|
|
613b0d9548 | ||
|
|
ed60a99826 | ||
|
|
61db0fba41 | ||
|
|
3c32cbb0af | ||
|
|
388ca351f4 | ||
|
|
b49742354d | ||
|
|
e13072cb42 | ||
|
|
6b3ad64388 | ||
|
|
66c22490c3 | ||
|
|
847d451505 | ||
|
|
325eaeb584 | ||
|
|
f06ba8e60b | ||
|
|
291ec743b6 | ||
|
|
760f727eb9 | ||
|
|
4c9db26541 | ||
|
|
50035ad414 | ||
|
|
49ec325f6a | ||
|
|
a1670c536d | ||
|
|
383aaca1eb | ||
|
|
42dd258c8d | ||
|
|
f63917a323 | ||
|
|
ef781cabcb | ||
|
|
c3a66b016b | ||
|
|
e1faf8327b | ||
|
|
2f1073dc6e | ||
|
|
81c16c965e | ||
|
|
a4668a16b6 | ||
|
|
9588721197 | ||
|
|
99c6c4a51b | ||
|
|
257ac2653a | ||
|
|
d11c9d7506 | ||
|
|
4ea4a92fe9 | ||
|
|
65f9c7d442 | ||
|
|
c185e39e59 | ||
|
|
1110183943 | ||
|
|
e62631350a | ||
|
|
e579fab4d0 | ||
|
|
6301a6660e | ||
|
|
711844ecd8 | ||
|
|
70ae2a4bce | ||
|
|
fc5c70a28d | ||
|
|
b58b0bd425 | ||
|
|
5bea443d94 | ||
|
|
79e4e46061 | ||
|
|
402b7beb87 | ||
|
|
a578da074b | ||
|
|
d76b830add | ||
|
|
65367aa24d | ||
|
|
4939cf18d8 | ||
|
|
7359740f36 | ||
|
|
1204d490d9 | ||
|
|
9c31b0ddcb | ||
|
|
6aee7a2032 | ||
|
|
74ff4a9ba9 | ||
|
|
1ecbff15fa | ||
|
|
7fd499a034 | ||
|
|
b8cd6d2e21 | ||
|
|
58dff34084 | ||
|
|
393c19bbcf | ||
|
|
b03df6fdb1 | ||
|
|
f4e6794dbd | ||
|
|
c5b51b35fb | ||
|
|
218a10179b | ||
|
|
4221ccf239 | ||
|
|
53057f33ed | ||
|
|
7cef38e865 | ||
|
|
b085ebd6db | ||
|
|
28c4dd05d0 | ||
|
|
88f6df4dcd | ||
|
|
8f86e66e5c | ||
|
|
f2ceeaa4a9 | ||
|
|
e2d85ff347 | ||
|
|
2c95b09a73 | ||
|
|
7d1d04495f | ||
|
|
d45066bef5 | ||
|
|
b174caa275 | ||
|
|
1b9734c45b | ||
|
|
8de4896bd6 | ||
|
|
f5b3fcc6cf | ||
|
|
0ba407fd9c | ||
|
|
af017121d2 | ||
|
|
40afb9dfb0 | ||
|
|
affb40340e | ||
|
|
e02b69aa0c | ||
|
|
a4d64adb32 | ||
|
|
a8c43f7af0 | ||
|
|
c6f7fa82ff | ||
|
|
4b6cd359e9 | ||
|
|
8dc2cb98b4 | ||
|
|
a433268db4 | ||
|
|
858bfc7a32 | ||
|
|
fdbe5b7aa7 | ||
|
|
bbdf53c79f | ||
|
|
f11456e2d3 | ||
|
|
049020f3c5 | ||
|
|
816096e642 | ||
|
|
6b9795849d |
@@ -1,4 +1,5 @@
|
||||
extensions
|
||||
extensions-disabled
|
||||
extensions-builtin/sd_forge_controlnet
|
||||
repositories
|
||||
venv
|
||||
@@ -86,8 +86,6 @@ module.exports = {
|
||||
// imageviewer.js
|
||||
modalPrevImage: "readonly",
|
||||
modalNextImage: "readonly",
|
||||
// token-counters.js
|
||||
setupTokenCounters: "readonly",
|
||||
// localStorage.js
|
||||
localSet: "readonly",
|
||||
localGet: "readonly",
|
||||
|
||||
52
.github/workflows/run_tests.yaml
vendored
@@ -4,9 +4,12 @@ on:
|
||||
- push
|
||||
- pull_request
|
||||
|
||||
env:
|
||||
FORGE_CQ_TEST: "True"
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: tests on CPU with empty model
|
||||
name: tests on CPU
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name
|
||||
steps:
|
||||
@@ -41,6 +44,29 @@ jobs:
|
||||
PYTHONUNBUFFERED: "1"
|
||||
- name: Print installed packages
|
||||
run: pip freeze
|
||||
- name: Download models
|
||||
run: |
|
||||
declare -a urls=(
|
||||
"https://huggingface.co/lllyasviel/fav_models/resolve/main/fav/realisticVisionV51_v51VAE.safetensors"
|
||||
)
|
||||
for url in "${urls[@]}"; do
|
||||
filename="models/Stable-diffusion/${url##*/}" # Extracts the last part of the URL
|
||||
if [ ! -f "$filename" ]; then
|
||||
curl -Lo "$filename" "$url"
|
||||
fi
|
||||
done
|
||||
# - name: Download ControlNet models
|
||||
# run: |
|
||||
# declare -a urls=(
|
||||
# "https://huggingface.co/lllyasviel/ControlNet-v1-1/resolve/main/control_v11p_sd15_canny.pth"
|
||||
# )
|
||||
|
||||
# for url in "${urls[@]}"; do
|
||||
# filename="models/ControlNet/${url##*/}" # Extracts the last part of the URL
|
||||
# if [ ! -f "$filename" ]; then
|
||||
# curl -Lo "$filename" "$url"
|
||||
# fi
|
||||
# done
|
||||
- name: Start test server
|
||||
run: >
|
||||
python -m coverage run
|
||||
@@ -52,30 +78,30 @@ jobs:
|
||||
--do-not-download-clip
|
||||
--no-half
|
||||
--disable-opt-split-attention
|
||||
--use-cpu all
|
||||
--always-cpu
|
||||
--api-server-stop
|
||||
--ckpt models/Stable-diffusion/realisticVisionV51_v51VAE.safetensors
|
||||
2>&1 | tee output.txt &
|
||||
- name: Run tests
|
||||
run: |
|
||||
wait-for-it --service 127.0.0.1:7860 -t 20
|
||||
python -m pytest -vv --junitxml=test/results.xml --cov . --cov-report=xml --verify-base-url test
|
||||
# TODO(huchenlei): Enable ControlNet tests. Currently it is too slow to run these tests on CPU with
|
||||
# real SD model. We need to find a way to load empty SD model.
|
||||
# - name: Run ControlNet tests
|
||||
# run: >
|
||||
# python -m pytest
|
||||
# --junitxml=test/results.xml
|
||||
# --cov ./extensions-builtin/sd_forge_controlnet
|
||||
# --cov-report=xml
|
||||
# --verify-base-url
|
||||
# ./extensions-builtin/sd_forge_controlnet/tests
|
||||
- name: Kill test server
|
||||
if: always()
|
||||
run: curl -vv -XPOST http://127.0.0.1:7860/sdapi/v1/server-stop && sleep 10
|
||||
- name: Show coverage
|
||||
run: |
|
||||
python -m coverage combine .coverage*
|
||||
python -m coverage report -i
|
||||
python -m coverage html -i
|
||||
- name: Upload main app output
|
||||
uses: actions/upload-artifact@v3
|
||||
if: always()
|
||||
with:
|
||||
name: output
|
||||
path: output.txt
|
||||
- name: Upload coverage HTML
|
||||
uses: actions/upload-artifact@v3
|
||||
if: always()
|
||||
with:
|
||||
name: htmlcov
|
||||
path: htmlcov
|
||||
|
||||
3
.gitignore
vendored
@@ -39,3 +39,6 @@ notification.mp3
|
||||
/package-lock.json
|
||||
/.coverage*
|
||||
/test/test_outputs
|
||||
/test/results.xml
|
||||
coverage.xml
|
||||
**/tests/**/expectations
|
||||
113
README.md
@@ -1,37 +1,26 @@
|
||||
# Stable Diffusion Web UI Forge
|
||||
# Stable Diffusion WebUI Forge
|
||||
|
||||
Stable Diffusion Web UI Forge is a platform on top of [Stable Diffusion WebUI](https://github.com/AUTOMATIC1111/stable-diffusion-webui) to make development easier, optimize resource management, and speed up inference.
|
||||
Stable Diffusion WebUI Forge is a platform on top of [Stable Diffusion WebUI](https://github.com/AUTOMATIC1111/stable-diffusion-webui) (based on [Gradio](https://www.gradio.app/)) to make development easier, optimize resource management, speed up inference, and study experimental features.
|
||||
|
||||
The name "Forge" is inspired from "Minecraft Forge". This project is aimed at becoming SD WebUI's Forge.
|
||||
|
||||
Compared to original WebUI (for SDXL inference at 1024px), you can expect the below speed-ups:
|
||||
|
||||
1. If you use common GPU like 8GB vram, you are expected to get about **30~45% speed up** in inference speed (it/s), the GPU memory peak (in task manager) will drop about 700MB to 1.3GB, the maximum diffusion resolution (that will not OOM) will increase about 2x to 3x, and the maximum diffusion batch size (that will not OOM) will increase about 4x to 6x.
|
||||
|
||||
2. If you use less powerful GPU like 6GB vram, you are expected to get about **60~75% speed up** in inference speed (it/s), the GPU memory peak (in task manager) will drop about 800MB to 1.5GB, the maximum diffusion resolution (that will not OOM) will increase about 3x, and the maximum diffusion batch size (that will not OOM) will increase about 4x.
|
||||
|
||||
3. If you use powerful GPU like 4090 with 24GB vram, you are expected to get about **3~6% speed up** in inference speed (it/s), the GPU memory peak (in task manager) will drop about 1GB to 1.4GB, the maximum diffusion resolution (that will not OOM) will increase about 1.6x, and the maximum diffusion batch size (that will not OOM) will increase about 2x.
|
||||
|
||||
4. If you use ControlNet for SDXL, the maximum ControlNet count (that will not OOM) will increase about 2x, the speed with SDXL+ControlNet will **speed up about 30~45%**.
|
||||
|
||||
Another very important change that Forge brings is **Unet Patcher**. Using Unet Patcher, methods like Self-Attention Guidance, Kohya High Res Fix, FreeU, StyleAlign, Hypertile can all be implemented in about 100 lines of codes.
|
||||
|
||||
Thanks to Unet Patcher, many new things are possible now and supported in Forge, including SVD, Z123, masked Ip-adapter, masked controlnet, photomaker, etc.
|
||||
|
||||
**No need to monkey patch UNet and conflict other extensions anymore!**
|
||||
This repo will undergo major change very recently. See also the [Announcement](https://github.com/lllyasviel/stable-diffusion-webui-forge/discussions/801).
|
||||
|
||||
# Installing Forge
|
||||
|
||||
You can install Forge using same method as SD-WebUI. (Install Git, Python, Git Clone this repo and then run webui-user.bat).
|
||||
If you are proficient in Git and you want to install Forge as another branch of SD-WebUI, please see [here](https://github.com/continue-revolution/sd-webui-animatediff/blob/forge/master/docs/how-to-use.md#you-have-a1111-and-you-know-git). In this way, you can reuse all SD checkpoints and all extensions you installed previously in your OG SD-WebUI, but you should know what you are doing.
|
||||
|
||||
If you know what you are doing, you can install Forge using same method as SD-WebUI. (Install Git, Python, Git Clone the forge repo `https://github.com/lllyasviel/stable-diffusion-webui-forge.git` and then run webui-user.bat).
|
||||
|
||||
**Or you can just use this one-click installation package (with git and python included).**
|
||||
|
||||
[>>> Click Here to Download One-Click Package<<<]()
|
||||
[>>> Click Here to Download One-Click Package<<<](https://github.com/lllyasviel/stable-diffusion-webui-forge/releases/download/latest/webui_forge_cu121_torch21.7z)
|
||||
|
||||
After you download, you can use `update.bat` to update and use `run.bat` to run.
|
||||
After you download, you uncompress, use `update.bat` to update, and use `run.bat` to run.
|
||||
|
||||

|
||||
Note that running `update.bat` is important, otherwise you may be using a previous version with potential bugs unfixed.
|
||||
|
||||

|
||||
|
||||
# Screenshots of Comparison
|
||||
|
||||
@@ -39,25 +28,25 @@ I tested with several devices, and this is a typical result from 8GB VRAM (3070t
|
||||
|
||||
**This is original WebUI:**
|
||||
|
||||

|
||||

|
||||
|
||||

|
||||

|
||||
|
||||

|
||||

|
||||
|
||||

|
||||

|
||||
|
||||
(average about 7.4GB/8GB, peak at about 7.9GB/8GB)
|
||||
|
||||
**This is WebUI Forge:**
|
||||
|
||||

|
||||

|
||||
|
||||

|
||||

|
||||
|
||||

|
||||

|
||||
|
||||

|
||||

|
||||
|
||||
(average and peak are all 6.3GB/8GB)
|
||||
|
||||
@@ -67,15 +56,21 @@ Forge can perfectly keep WebUI unchanged even for most complicated prompts like
|
||||
|
||||
All your previous works still work in Forge!
|
||||
|
||||
Also, Forge promise that we will only do our jobs. We will not add unnecessary opinioned changes to UI. You are still using 100% Automatic1111 WebUI.
|
||||
|
||||
# Forge Backend
|
||||
|
||||
Forge backend removes all WebUI's codes related to resource management and reworked everything. All previous CMD flags like `medvram, lowvram, medvram-sdxl, precision full, no half, no half vae, attention_xxx, upcast unet`, ... are all **REMOVED**. Adding these flags will not cause error but they will not do anything now. **We highly encourage Forge users to remove all cmd flags and let Forge to decide how to load models.**
|
||||
|
||||
Without any cmd flag, Forge can run SDXL with 4GB vram and SD1.5 with 2GB vram.
|
||||
|
||||
**The only one flag that you may still need** is `--always-offload-from-vram` (This flag will make things **slower**). This option will let Forge always unload models from VRAM. This can be useful if you use multiple software together and want Forge to use less VRAM and give some vram to other software, or when you are using some old extensions that will compete vram with Forge, or (very rarely) when you get OOM.
|
||||
**Some flags that you may still pay attention to:**
|
||||
|
||||
1. `--always-offload-from-vram` (This flag will make things **slower** but less risky). This option will let Forge always unload models from VRAM. This can be useful if you use multiple software together and want Forge to use less VRAM and give some VRAM to other software, or when you are using some old extensions that will compete vram with Forge, or (very rarely) when you get OOM.
|
||||
|
||||
2. `--cuda-malloc` (This flag will make things **faster** but more risky). This will ask pytorch to use *cudaMallocAsync* for tensor malloc. On some profilers I can observe performance gain at millisecond level, but the real speed up on most my devices are often unnoticed (about or less than 0.1 second per image). This cannot be set as default because many users reported issues that the async malloc will crash the program. Users need to enable this cmd flag at their own risk.
|
||||
|
||||
3. `--cuda-stream` (This flag will make things **faster** but more risky). This will use pytorch CUDA streams (a special type of thread on GPU) to move models and compute tensors simultaneously. This can almost eliminate all model moving time, and speed up SDXL on 30XX/40XX devices with small VRAM (eg, RTX 4050 6GB, RTX 3060 Laptop 6GB, etc) by about 15\% to 25\%. However, this unfortunately cannot be set as default because I observe higher possibility of pure black images (Nan outputs) on 2060, and higher chance of OOM on 1080 and 2060. When the resolution is large, there is a chance that the computation time of one single attention layer is longer than the time for moving entire model to GPU. When that happens, the next attention layer will OOM since the GPU is filled with the entire model, and no remaining space is available for computing another attention layer. Most overhead detecting methods are not robust enough to be reliable on old devices (in my tests). Users need to enable this cmd flag at their own risk.
|
||||
|
||||
4. `--pin-shared-memory` (This flag will make things **faster** but more risky). Effective only when used together with `--cuda-stream`. This will offload modules to Shared GPU Memory instead of system RAM when offloading models. On some 30XX/40XX devices with small VRAM (eg, RTX 4050 6GB, RTX 3060 Laptop 6GB, etc), I can observe significant (at least 20\%) speed-up for SDXL. However, this unfortunately cannot be set as default because the OOM of Shared GPU Memory is a much more severe problem than common GPU memory OOM. Pytorch does not provide any robust method to unload or detect Shared GPU Memory. Once the Shared GPU Memory OOM, the entire program will crash (observed with SDXL on GTX 1060/1050/1066), and there is no dynamic method to prevent or recover from the crash. Users need to enable this cmd flag at their own risk.
|
||||
|
||||
If you really want to play with cmd flags, you can additionally control the GPU with:
|
||||
|
||||
@@ -118,6 +113,8 @@ Again, Forge do not recommend users to use any cmd flags unless you are very sur
|
||||
|
||||
# UNet Patcher
|
||||
|
||||
Note that [Forge does not use any other software as backend](https://github.com/lllyasviel/stable-diffusion-webui-forge/discussions/169). The full name of the backend is `Stable Diffusion WebUI with Forge backend`, or for simplicity, the `Forge backend`. The API and python symbols are made similar to previous software only for reducing the learning cost of developers.
|
||||
|
||||
Now developing an extension is super simple. We finally have a patchable UNet.
|
||||
|
||||
Below is using one single file with 80 lines of codes to support FreeU:
|
||||
@@ -213,11 +210,11 @@ class FreeUForForge(scripts.Script):
|
||||
|
||||
It looks like this:
|
||||
|
||||

|
||||

|
||||
|
||||
Similar components like HyperTile, KohyaHighResFix, SAG, can all be implemented within 100 lines of codes (see also the codes).
|
||||
|
||||

|
||||

|
||||
|
||||
ControlNets can finally be called by different extensions.
|
||||
|
||||
@@ -343,14 +340,13 @@ Note that although the above codes look like independent codes, they actually wi
|
||||
|
||||
Note that this management is fully automatic. This makes writing extensions super simple.
|
||||
|
||||

|
||||

|
||||
|
||||
|
||||

|
||||

|
||||
|
||||
Similarly, Zero123:
|
||||
|
||||

|
||||

|
||||
|
||||
### Write a simple ControlNet:
|
||||
|
||||
@@ -526,7 +522,7 @@ if not cmd_opts.show_controlnet_example:
|
||||
|
||||
```
|
||||
|
||||

|
||||

|
||||
|
||||
|
||||
### Add a preprocessor
|
||||
@@ -626,29 +622,38 @@ Thanks to Unet Patcher, many new things are possible now and supported in Forge,
|
||||
|
||||
Masked Ip-Adapter
|
||||
|
||||

|
||||

|
||||
|
||||

|
||||
|
||||

|
||||

|
||||
|
||||

|
||||
|
||||
Masked ControlNet
|
||||
|
||||

|
||||

|
||||
|
||||

|
||||

|
||||
|
||||

|
||||

|
||||
|
||||
PhotoMaker
|
||||
|
||||

|
||||
(Note that photomaker is a special control that need you to add the trigger word "photomaker". Your prompt should be like "a photo of photomaker")
|
||||
|
||||

|
||||
|
||||
Marigold Depth
|
||||
|
||||

|
||||

|
||||
|
||||
# New Samplers (that are not in origin)
|
||||
|
||||
DDPM
|
||||
DDPM Karras
|
||||
DPM++ 2M Turbo
|
||||
DPM++ 2M SDE Turbo
|
||||
LCM Karras
|
||||
Euler A Turbo
|
||||
|
||||
# About Extensions
|
||||
|
||||
@@ -657,6 +662,8 @@ ControlNet and TiledVAE are integrated, and you should uninstall these two exten
|
||||
sd-webui-controlnet
|
||||
multidiffusion-upscaler-for-automatic1111
|
||||
|
||||
Note that **AnimateDiff** is under construction by [continue-revolution](https://github.com/continue-revolution) at [sd-webui-animatediff forge/master branch](https://github.com/continue-revolution/sd-webui-animatediff/tree/forge/master) and [sd-forge-animatediff](https://github.com/continue-revolution/sd-forge-animatediff) (they are in sync). (continue-revolution original words: prompt travel, inf t2v, controlnet v2v have been proven to work well; motion lora, i2i batch still under construction and may be finished in a week")
|
||||
|
||||
Other extensions should work without problems, like:
|
||||
|
||||
canvas-zoom
|
||||
@@ -668,4 +675,12 @@ Other extensions should work without problems, like:
|
||||
|
||||
However, if newer extensions use Forge, their codes can be much shorter.
|
||||
|
||||
Usually if an old extension can rework using Forge's unet patcher, 80% codes can be removed, especially when they need to call controlnet.
|
||||
Usually if an old extension rework using Forge's unet patcher, 80% codes can be removed, especially when they need to call controlnet.
|
||||
|
||||
# Contribution
|
||||
|
||||
Forge uses a bot to get commits and codes from https://github.com/AUTOMATIC1111/stable-diffusion-webui/tree/dev every afternoon (if merge is automatically successful by a git bot, or by my compiler, or by my ChatGPT bot) or mid-night (if my compiler and my ChatGPT bot both failed to merge and I review it manually).
|
||||
|
||||
All PRs that can be implemented in https://github.com/AUTOMATIC1111/stable-diffusion-webui/tree/dev should submit PRs there.
|
||||
|
||||
Feel free to submit PRs related to the functionality of Forge here.
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import os
|
||||
|
||||
from modules.modelloader import load_file_from_url
|
||||
from modules.upscaler import Upscaler, UpscalerData, prepare_free_memory
|
||||
from modules.upscaler import Upscaler, UpscalerData
|
||||
from modules_forge.forge_util import prepare_free_memory
|
||||
from ldsr_model_arch import LDSR
|
||||
from modules import shared, script_callbacks, errors
|
||||
import sd_hijack_autoencoder # noqa: F401
|
||||
|
||||
@@ -27,7 +27,10 @@ def assign_network_names_to_compvis_modules(sd_model):
|
||||
|
||||
|
||||
def load_network(name, network_on_disk):
|
||||
pass
|
||||
net = network.Network(name, network_on_disk)
|
||||
net.mtime = os.path.getmtime(network_on_disk.filename)
|
||||
|
||||
return net
|
||||
|
||||
|
||||
def purge_networks_from_memory():
|
||||
@@ -41,11 +44,23 @@ def load_networks(names, te_multipliers=None, unet_multipliers=None, dyn_dims=No
|
||||
if current_sd is None:
|
||||
return
|
||||
|
||||
loaded_networks.clear()
|
||||
|
||||
networks_on_disk = [available_networks.get(name, None) if name.lower() in forbidden_network_aliases else available_network_aliases.get(name, None) for name in names]
|
||||
if any(x is None for x in networks_on_disk):
|
||||
list_available_networks()
|
||||
networks_on_disk = [available_networks.get(name, None) if name.lower() in forbidden_network_aliases else available_network_aliases.get(name, None) for name in names]
|
||||
|
||||
for i, (network_on_disk, name) in enumerate(zip(networks_on_disk, names)):
|
||||
try:
|
||||
net = load_network(name, network_on_disk)
|
||||
except Exception as e:
|
||||
errors.display(e, f"loading network {network_on_disk.filename}")
|
||||
continue
|
||||
net.mentioned_name = name
|
||||
network_on_disk.read_hash()
|
||||
loaded_networks.append(net)
|
||||
|
||||
compiled_lora_targets = []
|
||||
for a, b, c in zip(networks_on_disk, unet_multipliers, te_multipliers):
|
||||
compiled_lora_targets.append([a.filename, b, c])
|
||||
@@ -62,7 +77,8 @@ def load_networks(names, te_multipliers=None, unet_multipliers=None, dyn_dims=No
|
||||
for filename, strength_model, strength_clip in compiled_lora_targets:
|
||||
lora_sd = load_lora_state_dict(filename)
|
||||
current_sd.forge_objects.unet, current_sd.forge_objects.clip = load_lora_for_models(
|
||||
current_sd.forge_objects.unet, current_sd.forge_objects.clip, lora_sd, strength_model, strength_clip)
|
||||
current_sd.forge_objects.unet, current_sd.forge_objects.clip, lora_sd, strength_model, strength_clip,
|
||||
filename=filename)
|
||||
|
||||
current_sd.forge_objects_after_applying_lora = current_sd.forge_objects.shallow_copy()
|
||||
return
|
||||
@@ -134,7 +150,6 @@ def list_available_networks():
|
||||
os.makedirs(shared.cmd_opts.lora_dir, exist_ok=True)
|
||||
|
||||
candidates = list(shared.walk_files(shared.cmd_opts.lora_dir, allowed_extensions=[".pt", ".ckpt", ".safetensors"]))
|
||||
candidates += list(shared.walk_files(shared.cmd_opts.lyco_dir_backcompat, allowed_extensions=[".pt", ".ckpt", ".safetensors"]))
|
||||
for filename in candidates:
|
||||
if os.path.isdir(filename):
|
||||
continue
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import os
|
||||
from modules import paths
|
||||
from modules.paths_internal import normalized_filepath
|
||||
|
||||
|
||||
def preload(parser):
|
||||
parser.add_argument("--lora-dir", type=str, help="Path to directory with Lora networks.", default=os.path.join(paths.models_path, 'Lora'))
|
||||
parser.add_argument("--lyco-dir-backcompat", type=str, help="Path to directory with LyCORIS networks (for backawards compatibility; can also use --lyco-dir).", default=os.path.join(paths.models_path, 'LyCORIS'))
|
||||
parser.add_argument("--lora-dir", type=normalized_filepath, help="Path to directory with Lora networks.", default=os.path.join(paths.models_path, 'Lora'))
|
||||
parser.add_argument("--lyco-dir-backcompat", type=normalized_filepath, help="Path to directory with LyCORIS networks (for backawards compatibility; can also use --lyco-dir).", default=os.path.join(paths.models_path, 'LyCORIS'))
|
||||
|
||||
@@ -21,7 +21,6 @@ def before_ui():
|
||||
|
||||
networks.extra_network_lora = extra_networks_lora.ExtraNetworkLora()
|
||||
extra_networks.register_extra_network(networks.extra_network_lora)
|
||||
extra_networks.register_extra_network_alias(networks.extra_network_lora, "lyco")
|
||||
|
||||
|
||||
networks.originals = lora_patches.LoraPatches()
|
||||
|
||||
@@ -84,7 +84,7 @@ class ExtraNetworksPageLora(ui_extra_networks.ExtraNetworksPage):
|
||||
yield item
|
||||
|
||||
def allowed_directories_for_previews(self):
|
||||
return [shared.cmd_opts.lora_dir, shared.cmd_opts.lyco_dir_backcompat]
|
||||
return [shared.cmd_opts.lora_dir]
|
||||
|
||||
def create_user_metadata_editor(self, ui, tabname):
|
||||
return LoraUserMetadataEditor(ui, tabname, self)
|
||||
|
||||
@@ -5,7 +5,8 @@ import torch
|
||||
from PIL import Image
|
||||
|
||||
from modules import devices, modelloader, script_callbacks, shared, upscaler_utils
|
||||
from modules.upscaler import Upscaler, UpscalerData, prepare_free_memory
|
||||
from modules.upscaler import Upscaler, UpscalerData
|
||||
from modules_forge.forge_util import prepare_free_memory
|
||||
|
||||
SWINIR_MODEL_URL = "https://github.com/JingyunLiang/SwinIR/releases/download/v0.0/003_realSR_BSRGAN_DFOWMFC_s64w8_SwinIR-L_x4_GAN.pth"
|
||||
|
||||
|
||||
@@ -76,6 +76,7 @@ def apply_leres(input_image, thr_a, thr_b, boost=False):
|
||||
with torch.no_grad():
|
||||
|
||||
if boost:
|
||||
pix2pixmodel.netG.to(devices.get_device_for("controlnet"))
|
||||
depth = estimateboost(input_image, model, 0, pix2pixmodel, max(width, height))
|
||||
else:
|
||||
depth = estimateleres(input_image, model, width, height)
|
||||
|
||||
@@ -63,13 +63,18 @@ def install_requirements(req_file):
|
||||
)
|
||||
|
||||
|
||||
def try_install_from_wheel(pkg_name: str, wheel_url: str):
|
||||
if get_installed_version(pkg_name) is not None:
|
||||
return
|
||||
|
||||
def try_install_from_wheel(pkg_name: str, wheel_url: str, version: Optional[str] = None):
|
||||
current_version = get_installed_version(pkg_name)
|
||||
if current_version is not None:
|
||||
# No version requirement.
|
||||
if version is None:
|
||||
return
|
||||
# Version requirement already satisfied.
|
||||
if comparable_version(current_version) >= comparable_version(version):
|
||||
return
|
||||
try:
|
||||
launch.run_pip(
|
||||
f"install {wheel_url}",
|
||||
f"install -U {wheel_url}",
|
||||
f"forge_legacy_preprocessor requirement: {pkg_name}",
|
||||
)
|
||||
except Exception as e:
|
||||
@@ -132,8 +137,9 @@ try_install_from_wheel(
|
||||
"handrefinerportable",
|
||||
wheel_url=os.environ.get(
|
||||
"HANDREFINER_WHEEL",
|
||||
"https://github.com/huchenlei/HandRefinerPortable/releases/download/v1.0.0/handrefinerportable-2024.1.18.0-py2.py3-none-any.whl",
|
||||
"https://github.com/huchenlei/HandRefinerPortable/releases/download/v1.0.1/handrefinerportable-2024.2.12.0-py2.py3-none-any.whl",
|
||||
),
|
||||
version="2024.2.12.0",
|
||||
)
|
||||
try_install_from_wheel(
|
||||
"depth_anything",
|
||||
|
||||
@@ -615,7 +615,8 @@ legacy_preprocessors = {
|
||||
"priority": 100,
|
||||
"tags": [
|
||||
"MLSD"
|
||||
]
|
||||
],
|
||||
"use_soft_projection_in_hr_fix": True
|
||||
},
|
||||
# "normal_bae": {
|
||||
# "label": "normal_bae",
|
||||
|
||||
@@ -59,6 +59,9 @@ class LegacyPreprocessor(Preprocessor):
|
||||
'instant-iD': ['instant_id', 'instantid'],
|
||||
}
|
||||
|
||||
if legacy_dict.get('use_soft_projection_in_hr_fix', False):
|
||||
self.use_soft_projection_in_hr_fix = True
|
||||
|
||||
self.model_filename_filters = []
|
||||
for tag in self.tags:
|
||||
tag_lower = tag.lower()
|
||||
@@ -108,7 +111,10 @@ class LegacyPreprocessor(Preprocessor):
|
||||
return result
|
||||
|
||||
|
||||
for k, v in legacy_preprocessors.items():
|
||||
p = LegacyPreprocessor(v)
|
||||
p.name = k
|
||||
for name, data in legacy_preprocessors.items():
|
||||
p = LegacyPreprocessor(data)
|
||||
p.name = name
|
||||
# Invert should not match any particular model.
|
||||
if "invert" in name:
|
||||
p.model_filename_filters = []
|
||||
add_supported_preprocessor(p)
|
||||
|
||||
@@ -20,6 +20,8 @@ class PreprocessorInpaint(Preprocessor):
|
||||
self.tags = ['Inpaint']
|
||||
self.model_filename_filters = ['inpaint']
|
||||
self.slider_resolution = PreprocessorParameter(visible=False)
|
||||
self.fill_mask_with_one_when_resize_and_fill = True
|
||||
self.expand_mask_when_resize_and_fill = True
|
||||
|
||||
def process_before_every_sampling(self, process, cond, mask, *args, **kwargs):
|
||||
mask = mask.round()
|
||||
@@ -34,7 +36,6 @@ class PreprocessorInpaintOnly(PreprocessorInpaint):
|
||||
self.image = None
|
||||
self.mask = None
|
||||
self.latent = None
|
||||
self.fill_mask_with_one_when_resize_and_fill = True
|
||||
|
||||
def process_before_every_sampling(self, process, cond, mask, *args, **kwargs):
|
||||
mask = mask.round()
|
||||
@@ -55,11 +56,17 @@ class PreprocessorInpaintOnly(PreprocessorInpaint):
|
||||
|
||||
unet = process.sd_model.forge_objects.unet.clone()
|
||||
|
||||
def pre_cfg(model, c, uc, x, timestep, model_options):
|
||||
noisy_latent = latent_image.to(x) + timestep[:, None, None, None].to(x) * torch.randn_like(latent_image).to(x)
|
||||
x = x * latent_mask.to(x) + noisy_latent.to(x) * (1.0 - latent_mask.to(x))
|
||||
return model, c, uc, x, timestep, model_options
|
||||
|
||||
def post_cfg(args):
|
||||
denoised = args['denoised']
|
||||
denoised = denoised * latent_mask.to(denoised) + latent_image.to(denoised) * (1.0 - latent_mask.to(denoised))
|
||||
return denoised
|
||||
|
||||
unet.add_sampler_pre_cfg_function(pre_cfg)
|
||||
unet.set_model_sampler_post_cfg_function(post_cfg)
|
||||
|
||||
process.sd_model.forge_objects.unet = unet
|
||||
|
||||
@@ -44,7 +44,11 @@ class PreprocessorTileColorFix(PreprocessorTile):
|
||||
|
||||
unet = process.sd_model.forge_objects.unet.clone()
|
||||
sigma_data = process.sd_model.forge_objects.unet.model.model_sampling.sigma_data
|
||||
k = int(self.variation)
|
||||
|
||||
if getattr(process, 'is_hr_pass', False):
|
||||
k = int(self.variation * 2)
|
||||
else:
|
||||
k = int(self.variation)
|
||||
|
||||
def block_proc(h, flag, transformer_options):
|
||||
location, block_id = transformer_options['block']
|
||||
|
||||
112
extensions-builtin/sd_forge_controlnet/lib_controlnet/api.py
Normal file
@@ -0,0 +1,112 @@
|
||||
from typing import List
|
||||
|
||||
import numpy as np
|
||||
from fastapi import FastAPI, Body
|
||||
from fastapi.exceptions import HTTPException
|
||||
from PIL import Image
|
||||
import gradio as gr
|
||||
|
||||
from modules.api import api
|
||||
from .global_state import (
|
||||
get_all_preprocessor_names,
|
||||
get_all_controlnet_names,
|
||||
get_preprocessor,
|
||||
)
|
||||
from .utils import judge_image_type
|
||||
from .logging import logger
|
||||
|
||||
|
||||
def encode_to_base64(image):
|
||||
if isinstance(image, str):
|
||||
return image
|
||||
elif not judge_image_type(image):
|
||||
return "Detect result is not image"
|
||||
elif isinstance(image, Image.Image):
|
||||
return api.encode_pil_to_base64(image)
|
||||
elif isinstance(image, np.ndarray):
|
||||
return encode_np_to_base64(image)
|
||||
else:
|
||||
logger.warn("Unable to encode image.")
|
||||
return ""
|
||||
|
||||
|
||||
def encode_np_to_base64(image):
|
||||
pil = Image.fromarray(image)
|
||||
return api.encode_pil_to_base64(pil)
|
||||
|
||||
|
||||
def controlnet_api(_: gr.Blocks, app: FastAPI):
|
||||
@app.get("/controlnet/model_list")
|
||||
async def model_list():
|
||||
up_to_date_model_list = get_all_controlnet_names()
|
||||
logger.debug(up_to_date_model_list)
|
||||
return {"model_list": up_to_date_model_list}
|
||||
|
||||
@app.get("/controlnet/module_list")
|
||||
async def module_list():
|
||||
module_list = get_all_preprocessor_names()
|
||||
logger.debug(module_list)
|
||||
|
||||
return {
|
||||
"module_list": module_list,
|
||||
# TODO: Add back module detail.
|
||||
# "module_detail": external_code.get_modules_detail(alias_names),
|
||||
}
|
||||
|
||||
@app.post("/controlnet/detect")
|
||||
async def detect(
|
||||
controlnet_module: str = Body("none", title="Controlnet Module"),
|
||||
controlnet_input_images: List[str] = Body([], title="Controlnet Input Images"),
|
||||
controlnet_processor_res: int = Body(
|
||||
512, title="Controlnet Processor Resolution"
|
||||
),
|
||||
controlnet_threshold_a: float = Body(64, title="Controlnet Threshold a"),
|
||||
controlnet_threshold_b: float = Body(64, title="Controlnet Threshold b"),
|
||||
):
|
||||
processor_module = get_preprocessor(controlnet_module)
|
||||
if processor_module is None:
|
||||
raise HTTPException(status_code=422, detail="Module not available")
|
||||
|
||||
if len(controlnet_input_images) == 0:
|
||||
raise HTTPException(status_code=422, detail="No image selected")
|
||||
|
||||
logger.debug(
|
||||
f"Detecting {str(len(controlnet_input_images))} images with the {controlnet_module} module."
|
||||
)
|
||||
|
||||
results = []
|
||||
poses = []
|
||||
|
||||
for input_image in controlnet_input_images:
|
||||
img = np.array(api.decode_base64_to_image(input_image)).astype('uint8')
|
||||
|
||||
class JsonAcceptor:
|
||||
def __init__(self) -> None:
|
||||
self.value = None
|
||||
|
||||
def accept(self, json_dict: dict) -> None:
|
||||
self.value = json_dict
|
||||
|
||||
json_acceptor = JsonAcceptor()
|
||||
|
||||
results.append(
|
||||
processor_module(
|
||||
img,
|
||||
resolution=controlnet_processor_res,
|
||||
slider_1=controlnet_threshold_a,
|
||||
slider_2=controlnet_threshold_b,
|
||||
json_pose_callback=json_acceptor.accept,
|
||||
)
|
||||
)
|
||||
|
||||
if "openpose" in controlnet_module:
|
||||
assert json_acceptor.value is not None
|
||||
poses.append(json_acceptor.value)
|
||||
|
||||
results64 = [encode_to_base64(img) for img in results]
|
||||
res = {"images": results64, "info": "Success"}
|
||||
if poses:
|
||||
res["poses"] = poses
|
||||
|
||||
return res
|
||||
|
||||
@@ -16,8 +16,8 @@ from lib_controlnet.controlnet_ui.openpose_editor import OpenposeEditor
|
||||
from lib_controlnet.controlnet_ui.preset import ControlNetPresetUI
|
||||
from lib_controlnet.controlnet_ui.tool_button import ToolButton
|
||||
from lib_controlnet.controlnet_ui.photopea import Photopea
|
||||
from lib_controlnet.enums import InputMode
|
||||
from modules import shared
|
||||
from lib_controlnet.enums import InputMode, HiResFixOption
|
||||
from modules import shared, script_callbacks
|
||||
from modules.ui_components import FormRow
|
||||
from modules_forge.forge_util import HWC3
|
||||
from lib_controlnet.external_code import UiControlNetUnit
|
||||
@@ -46,9 +46,7 @@ class A1111Context:
|
||||
img2img_inpaint_upload_tab: Optional[gr.components.IOComponent] = None
|
||||
|
||||
img2img_inpaint_area: Optional[gr.components.IOComponent] = None
|
||||
# txt2img_enable_hr is only available for A1111 > 1.7.0.
|
||||
txt2img_enable_hr: Optional[gr.components.IOComponent] = None
|
||||
setting_sd_model_checkpoint: Optional[gr.components.IOComponent] = None
|
||||
|
||||
@property
|
||||
def img2img_inpaint_tabs(self) -> Tuple[gr.components.IOComponent]:
|
||||
@@ -76,10 +74,6 @@ class A1111Context:
|
||||
"img2img_inpaint_tab": "img2img_inpaint_tab",
|
||||
"img2img_inpaint_sketch_tab": "img2img_inpaint_sketch_tab",
|
||||
"img2img_inpaint_upload_tab": "img2img_inpaint_upload_tab",
|
||||
# SDNext does not have this field. Temporarily disable the callback on
|
||||
# the checkpoint change until we find a way to register an event when
|
||||
# all A1111 UI components are ready.
|
||||
"setting_sd_model_checkpoint": "setting_sd_model_checkpoint",
|
||||
}
|
||||
return all(
|
||||
c
|
||||
@@ -105,8 +99,6 @@ class A1111Context:
|
||||
"img2img_inpaint_upload_tab": "img2img_inpaint_upload_tab",
|
||||
"img2img_inpaint_full_res": "img2img_inpaint_area",
|
||||
"txt2img_hr-checkbox": "txt2img_enable_hr",
|
||||
# setting_sd_model_checkpoint is expected to be initialized last.
|
||||
# "setting_sd_model_checkpoint": "setting_sd_model_checkpoint",
|
||||
}
|
||||
elem_id = getattr(component, "elem_id", None)
|
||||
# Do not set component if it has already been set.
|
||||
@@ -180,10 +172,11 @@ class ControlNetUiGroup(object):
|
||||
|
||||
# Note: All gradio elements declared in `render` will be defined as member variable.
|
||||
# Update counter to trigger a force update of UiControlNetUnit.
|
||||
# This is useful when a field with no event subscriber available changes.
|
||||
# e.g. gr.Gallery, gr.State, etc.
|
||||
# dummy_gradio_update_trigger is useful when a field with no event subscriber available changes.
|
||||
# e.g. gr.Gallery, gr.State, etc. After an update to gr.State / gr.Gallery, please increment
|
||||
# this counter to trigger a sync update of UiControlNetUnit.
|
||||
self.dummy_gradio_update_trigger = None
|
||||
self.enabled = None
|
||||
self.update_unit_counter = None
|
||||
self.upload_tab = None
|
||||
self.image = None
|
||||
self.generated_image_group = None
|
||||
@@ -193,7 +186,7 @@ class ControlNetUiGroup(object):
|
||||
self.batch_tab = None
|
||||
self.batch_image_dir = None
|
||||
self.merge_tab = None
|
||||
self.merge_gallery = None
|
||||
self.batch_input_gallery = None
|
||||
self.merge_upload_button = None
|
||||
self.merge_clear_button = None
|
||||
self.create_canvas = None
|
||||
@@ -251,7 +244,7 @@ class ControlNetUiGroup(object):
|
||||
Returns:
|
||||
None
|
||||
"""
|
||||
self.update_unit_counter = gr.Number(value=0, visible=False)
|
||||
self.dummy_gradio_update_trigger = gr.Number(value=0, visible=False)
|
||||
self.openpose_editor = OpenposeEditor()
|
||||
|
||||
with gr.Group(visible=not self.is_img2img) as self.image_upload_panel:
|
||||
@@ -324,26 +317,45 @@ class ControlNetUiGroup(object):
|
||||
else None,
|
||||
)
|
||||
|
||||
with gr.Tab(label="Batch") as self.batch_tab:
|
||||
gr.HTML('Batch system is under maintaining now ... Please come back later ...')
|
||||
self.batch_image_dir = gr.Textbox(
|
||||
label="Input Directory",
|
||||
placeholder="Leave empty to use img2img batch controlnet input directory",
|
||||
elem_id=f"{elem_id_tabname}_{tabname}_batch_image_dir",
|
||||
)
|
||||
|
||||
with gr.Tab(label="Multiple Images") as self.merge_tab:
|
||||
gr.HTML('Multi-image system is under maintaining now ... Please come back later ...')
|
||||
self.merge_gallery = gr.Gallery(
|
||||
columns=[4], rows=[2], object_fit="contain", height="auto"
|
||||
)
|
||||
with gr.Tab(label="Batch Folder") as self.batch_tab:
|
||||
with gr.Row():
|
||||
self.merge_upload_button = gr.UploadButton(
|
||||
"Upload Images",
|
||||
file_types=["image"],
|
||||
file_count="multiple",
|
||||
self.batch_image_dir = gr.Textbox(
|
||||
label="Input Directory",
|
||||
placeholder="Input directory path to the control images.",
|
||||
elem_id=f"{elem_id_tabname}_{tabname}_batch_image_dir",
|
||||
)
|
||||
self.merge_clear_button = gr.Button("Clear Images")
|
||||
self.batch_mask_dir = gr.Textbox(
|
||||
label="Mask Directory",
|
||||
placeholder="Mask directory path to the control images.",
|
||||
elem_id=f"{elem_id_tabname}_{tabname}_batch_mask_dir",
|
||||
visible=False,
|
||||
)
|
||||
|
||||
with gr.Tab(label="Batch Upload") as self.merge_tab:
|
||||
with gr.Row():
|
||||
with gr.Column():
|
||||
self.batch_input_gallery = gr.Gallery(
|
||||
columns=[4], rows=[2], object_fit="contain", height="auto", label="Images"
|
||||
)
|
||||
with gr.Row():
|
||||
self.merge_upload_button = gr.UploadButton(
|
||||
"Upload Images",
|
||||
file_types=["image"],
|
||||
file_count="multiple",
|
||||
)
|
||||
self.merge_clear_button = gr.Button("Clear Images")
|
||||
with gr.Group(visible=False, elem_classes=["cnet-mask-gallery-group"]) as self.batch_mask_gallery_group:
|
||||
with gr.Column():
|
||||
self.batch_mask_gallery = gr.Gallery(
|
||||
columns=[4], rows=[2], object_fit="contain", height="auto", label="Masks"
|
||||
)
|
||||
with gr.Row():
|
||||
self.mask_merge_upload_button = gr.UploadButton(
|
||||
"Upload Masks",
|
||||
file_types=["image"],
|
||||
file_count="multiple",
|
||||
)
|
||||
self.mask_merge_clear_button = gr.Button("Clear Masks")
|
||||
|
||||
if self.photopea:
|
||||
self.photopea.attach_photopea_output(self.generated_image)
|
||||
@@ -560,15 +572,15 @@ class ControlNetUiGroup(object):
|
||||
visible=not self.is_img2img,
|
||||
)
|
||||
|
||||
# self.hr_option = gr.Radio(
|
||||
# choices=[e.value for e in external_code.HiResFixOption],
|
||||
# value=self.default_unit.hr_option.value,
|
||||
# label="Hires-Fix Option",
|
||||
# elem_id=f"{elem_id_tabname}_{tabname}_controlnet_hr_option_radio",
|
||||
# elem_classes="controlnet_hr_option_radio",
|
||||
# visible=False,
|
||||
# )
|
||||
#
|
||||
self.hr_option = gr.Radio(
|
||||
choices=[e.value for e in HiResFixOption],
|
||||
value=self.default_unit.hr_option.value,
|
||||
label="Hires-Fix Option",
|
||||
elem_id=f"{elem_id_tabname}_{tabname}_controlnet_hr_option_radio",
|
||||
elem_classes="controlnet_hr_option_radio",
|
||||
visible=False,
|
||||
)
|
||||
|
||||
# self.loopback = gr.Checkbox(
|
||||
# label="[Batch Loopback] Automatically send generated images to this ControlNet unit in batch generation",
|
||||
# value=self.default_unit.loopback,
|
||||
@@ -586,8 +598,13 @@ class ControlNetUiGroup(object):
|
||||
unit_args = (
|
||||
self.input_mode,
|
||||
self.use_preview_as_input,
|
||||
self.batch_image_dir,
|
||||
self.batch_mask_dir,
|
||||
self.batch_input_gallery,
|
||||
self.batch_mask_gallery,
|
||||
self.generated_image,
|
||||
self.mask_image,
|
||||
self.hr_option,
|
||||
self.enabled,
|
||||
self.module,
|
||||
self.model,
|
||||
@@ -604,7 +621,7 @@ class ControlNetUiGroup(object):
|
||||
)
|
||||
|
||||
unit = gr.State(self.default_unit)
|
||||
for comp in unit_args + (self.update_unit_counter,):
|
||||
for comp in unit_args + (self.dummy_gradio_update_trigger,):
|
||||
event_subscribers = []
|
||||
if hasattr(comp, "edit"):
|
||||
event_subscribers.append(comp.edit)
|
||||
@@ -833,7 +850,6 @@ class ControlNetUiGroup(object):
|
||||
slider_1=pthr_a,
|
||||
slider_2=pthr_b,
|
||||
input_mask=mask,
|
||||
low_vram=shared.opts.data.get("controlnet_clip_detector_on_cpu", False),
|
||||
json_pose_callback=json_acceptor.accept
|
||||
if is_openpose(module)
|
||||
else None,
|
||||
@@ -954,23 +970,31 @@ class ControlNetUiGroup(object):
|
||||
return
|
||||
|
||||
def register_shift_hr_options(self):
|
||||
return
|
||||
ControlNetUiGroup.a1111_context.txt2img_enable_hr.change(
|
||||
fn=lambda checked: gr.update(visible=checked),
|
||||
inputs=[ControlNetUiGroup.a1111_context.txt2img_enable_hr],
|
||||
outputs=[self.hr_option],
|
||||
show_progress=False,
|
||||
)
|
||||
|
||||
def register_shift_upload_mask(self):
|
||||
"""Controls whether the upload mask input should be visible."""
|
||||
def on_checkbox_click(checked: bool, canvas_height: int, canvas_width: int):
|
||||
if not checked:
|
||||
# Clear mask_image if unchecked.
|
||||
return gr.update(visible=False), gr.update(value=None)
|
||||
return gr.update(visible=False), gr.update(value=None), gr.update(value=None, visible=False), \
|
||||
gr.update(visible=False), gr.update(value=None)
|
||||
else:
|
||||
# Init an empty canvas the same size as the generation target.
|
||||
empty_canvas = np.zeros(shape=(canvas_height, canvas_width, 3), dtype=np.uint8)
|
||||
return gr.update(visible=True), gr.update(value=empty_canvas)
|
||||
return gr.update(visible=True), gr.update(value=empty_canvas), gr.update(visible=True), \
|
||||
gr.update(visible=True), gr.update()
|
||||
|
||||
self.mask_upload.change(
|
||||
fn=on_checkbox_click,
|
||||
inputs=[self.mask_upload, self.height_slider, self.width_slider],
|
||||
outputs=[self.mask_image_group, self.mask_image],
|
||||
outputs=[self.mask_image_group, self.mask_image, self.batch_mask_dir,
|
||||
self.batch_mask_gallery_group, self.batch_mask_gallery],
|
||||
show_progress=False,
|
||||
)
|
||||
|
||||
@@ -1054,32 +1078,51 @@ class ControlNetUiGroup(object):
|
||||
)
|
||||
|
||||
def register_multi_images_upload(self):
|
||||
# """Register callbacks on merge tab multiple images upload."""
|
||||
# self.merge_clear_button.click(
|
||||
# fn=lambda: [],
|
||||
# inputs=[],
|
||||
# outputs=[self.merge_gallery],
|
||||
# ).then(
|
||||
# fn=lambda x: gr.update(value=x + 1),
|
||||
# inputs=[self.update_unit_counter],
|
||||
# outputs=[self.update_unit_counter],
|
||||
# )
|
||||
#
|
||||
# def upload_file(files, current_files):
|
||||
# return {file_d["name"] for file_d in current_files} | {
|
||||
# file.name for file in files
|
||||
# }
|
||||
#
|
||||
# self.merge_upload_button.upload(
|
||||
# upload_file,
|
||||
# inputs=[self.merge_upload_button, self.merge_gallery],
|
||||
# outputs=[self.merge_gallery],
|
||||
# queue=False,
|
||||
# ).then(
|
||||
# fn=lambda x: gr.update(value=x + 1),
|
||||
# inputs=[self.update_unit_counter],
|
||||
# outputs=[self.update_unit_counter],
|
||||
# )
|
||||
"""Register callbacks on merge tab multiple images upload."""
|
||||
self.merge_clear_button.click(
|
||||
fn=lambda: [],
|
||||
inputs=[],
|
||||
outputs=[self.batch_input_gallery],
|
||||
).then(
|
||||
fn=lambda x: gr.update(value=x + 1),
|
||||
inputs=[self.dummy_gradio_update_trigger],
|
||||
outputs=[self.dummy_gradio_update_trigger],
|
||||
)
|
||||
self.mask_merge_clear_button.click(
|
||||
fn=lambda: [],
|
||||
inputs=[],
|
||||
outputs=[self.batch_mask_gallery],
|
||||
).then(
|
||||
fn=lambda x: gr.update(value=x + 1),
|
||||
inputs=[self.dummy_gradio_update_trigger],
|
||||
outputs=[self.dummy_gradio_update_trigger],
|
||||
)
|
||||
|
||||
def upload_file(files, current_files):
|
||||
return {file_d["name"] for file_d in current_files} | {
|
||||
file.name for file in files
|
||||
}
|
||||
|
||||
self.merge_upload_button.upload(
|
||||
upload_file,
|
||||
inputs=[self.merge_upload_button, self.batch_input_gallery],
|
||||
outputs=[self.batch_input_gallery],
|
||||
queue=False,
|
||||
).then(
|
||||
fn=lambda x: gr.update(value=x + 1),
|
||||
inputs=[self.dummy_gradio_update_trigger],
|
||||
outputs=[self.dummy_gradio_update_trigger],
|
||||
)
|
||||
self.mask_merge_upload_button.upload(
|
||||
upload_file,
|
||||
inputs=[self.mask_merge_upload_button, self.batch_mask_gallery],
|
||||
outputs=[self.batch_mask_gallery],
|
||||
queue=False,
|
||||
).then(
|
||||
fn=lambda x: gr.update(value=x + 1),
|
||||
inputs=[self.dummy_gradio_update_trigger],
|
||||
outputs=[self.dummy_gradio_update_trigger],
|
||||
)
|
||||
return
|
||||
|
||||
def register_core_callbacks(self):
|
||||
@@ -1090,7 +1133,6 @@ class ControlNetUiGroup(object):
|
||||
self.register_refresh_all_models()
|
||||
self.register_build_sliders()
|
||||
self.register_shift_preview()
|
||||
self.register_shift_upload_mask()
|
||||
self.register_create_canvas()
|
||||
self.register_clear_preview()
|
||||
self.register_multi_images_upload()
|
||||
@@ -1105,12 +1147,32 @@ class ControlNetUiGroup(object):
|
||||
self.type_filter,
|
||||
*[
|
||||
getattr(self, key)
|
||||
for key in vars(external_code.ControlNetUnit()).keys()
|
||||
for key in external_code.ControlNetUnit.infotext_fields()
|
||||
],
|
||||
)
|
||||
if self.is_img2img:
|
||||
self.register_img2img_same_input()
|
||||
|
||||
def register_sd_model_changed(self):
|
||||
def sd_version_changed(type_filter: str, current_model: str, setting_value: str, setting_name: str):
|
||||
"""When SD version changes, update model dropdown choices."""
|
||||
if setting_name != "sd_model_checkpoint":
|
||||
return gr.update()
|
||||
|
||||
filtered_model_list = global_state.get_filtered_controlnet_names(type_filter)
|
||||
assert len(filtered_model_list) > 0
|
||||
default_model = filtered_model_list[1] if len(filtered_model_list) > 1 else filtered_model_list[0]
|
||||
return gr.Dropdown.update(
|
||||
choices=filtered_model_list,
|
||||
value=current_model if current_model in filtered_model_list else default_model
|
||||
)
|
||||
|
||||
script_callbacks.on_setting_updated_subscriber(dict(
|
||||
fn=sd_version_changed,
|
||||
inputs=[self.type_filter, self.model],
|
||||
outputs=[self.model],
|
||||
))
|
||||
|
||||
def register_callbacks(self):
|
||||
"""Register callbacks that involves A1111 context gradio components."""
|
||||
# Prevent infinite recursion.
|
||||
@@ -1121,6 +1183,8 @@ class ControlNetUiGroup(object):
|
||||
self.register_send_dimensions()
|
||||
self.register_run_annotator()
|
||||
self.register_sync_batch_dir()
|
||||
self.register_shift_upload_mask()
|
||||
self.register_sd_model_changed()
|
||||
if self.is_img2img:
|
||||
self.register_shift_crop_input_image()
|
||||
else:
|
||||
|
||||
@@ -7,7 +7,9 @@ from modules import scripts
|
||||
from lib_controlnet.infotext import parse_unit, serialize_unit
|
||||
from lib_controlnet.controlnet_ui.tool_button import ToolButton
|
||||
from lib_controlnet.logging import logger
|
||||
from lib_controlnet import external_code
|
||||
from lib_controlnet.external_code import ControlNetUnit, UiControlNetUnit
|
||||
from lib_controlnet.global_state import get_preprocessor
|
||||
from modules_forge.supported_preprocessor import Preprocessor
|
||||
|
||||
save_symbol = "\U0001f4be" # 💾
|
||||
delete_symbol = "\U0001f5d1\ufe0f" # 🗑️
|
||||
@@ -33,24 +35,10 @@ def load_presets(preset_dir: str) -> Dict[str, str]:
|
||||
return presets
|
||||
|
||||
|
||||
def infer_control_type(module: str, model: str) -> str:
|
||||
def matches_control_type(input_string: str, control_type: str) -> bool:
|
||||
return any(t.lower() in input_string for t in control_type.split("/"))
|
||||
|
||||
control_types = preprocessor_filters.keys()
|
||||
control_type_candidates = [
|
||||
control_type
|
||||
for control_type in control_types
|
||||
if (
|
||||
matches_control_type(module, control_type)
|
||||
or matches_control_type(model, control_type)
|
||||
)
|
||||
]
|
||||
if len(control_type_candidates) != 1:
|
||||
raise ValueError(
|
||||
f"Unable to infer control type from module {module} and model {model}"
|
||||
)
|
||||
return control_type_candidates[0]
|
||||
def infer_control_type(module: str) -> str:
|
||||
preprocessor: Preprocessor = get_preprocessor(module)
|
||||
assert preprocessor is not None
|
||||
return preprocessor.tags[0] if preprocessor.tags else "All"
|
||||
|
||||
|
||||
class ControlNetPresetUI(object):
|
||||
@@ -111,13 +99,19 @@ class ControlNetPresetUI(object):
|
||||
control_type: gr.Radio,
|
||||
*ui_states,
|
||||
):
|
||||
def init_with_ui_states(*ui_states) -> ControlNetUnit:
|
||||
return ControlNetUnit(**{
|
||||
field: value
|
||||
for field, value in zip(ControlNetUnit.infotext_fields(), ui_states)
|
||||
})
|
||||
|
||||
def apply_preset(name: str, control_type: str, *ui_states):
|
||||
if name == NEW_PRESET:
|
||||
return (
|
||||
gr.update(visible=False),
|
||||
*(
|
||||
(gr.skip(),)
|
||||
* (len(vars(external_code.ControlNetUnit()).keys()) + 1)
|
||||
* (len(ControlNetUnit.infotext_fields()) + 1)
|
||||
),
|
||||
)
|
||||
|
||||
@@ -125,7 +119,7 @@ class ControlNetPresetUI(object):
|
||||
|
||||
infotext = ControlNetPresetUI.presets[name]
|
||||
preset_unit = parse_unit(infotext)
|
||||
current_unit = external_code.ControlNetUnit(*ui_states)
|
||||
current_unit = init_with_ui_states(*ui_states)
|
||||
preset_unit.image = None
|
||||
current_unit.image = None
|
||||
|
||||
@@ -140,14 +134,14 @@ class ControlNetPresetUI(object):
|
||||
gr.update(visible=False),
|
||||
*(
|
||||
(gr.skip(),)
|
||||
* (len(vars(external_code.ControlNetUnit()).keys()) + 1)
|
||||
* (len(ControlNetUnit.infotext_fields()) + 1)
|
||||
),
|
||||
)
|
||||
|
||||
unit = preset_unit
|
||||
|
||||
try:
|
||||
new_control_type = infer_control_type(unit.module, unit.model)
|
||||
new_control_type = infer_control_type(unit.module)
|
||||
except ValueError as e:
|
||||
logger.error(e)
|
||||
new_control_type = control_type
|
||||
@@ -166,7 +160,8 @@ class ControlNetPresetUI(object):
|
||||
gr.update(value=new_control_type),
|
||||
*[
|
||||
gr.update(value=value) if value is not None else gr.update()
|
||||
for value in vars(unit).values()
|
||||
for field in ControlNetUnit.infotext_fields()
|
||||
for value in (getattr(unit, field),)
|
||||
],
|
||||
)
|
||||
|
||||
@@ -190,7 +185,7 @@ class ControlNetPresetUI(object):
|
||||
return gr.update(visible=True), gr.update(), gr.update()
|
||||
|
||||
ControlNetPresetUI.save_preset(
|
||||
name, external_code.ControlNetUnit(*ui_states)
|
||||
name, init_with_ui_states(*ui_states)
|
||||
)
|
||||
return (
|
||||
gr.update(), # name dialog
|
||||
@@ -235,7 +230,7 @@ class ControlNetPresetUI(object):
|
||||
return gr.update(visible=False), gr.update()
|
||||
|
||||
ControlNetPresetUI.save_preset(
|
||||
new_name, external_code.ControlNetUnit(*ui_states)
|
||||
new_name, init_with_ui_states(*ui_states)
|
||||
)
|
||||
return gr.update(visible=False), gr.update(
|
||||
choices=ControlNetPresetUI.dropdown_choices(), value=new_name
|
||||
@@ -261,7 +256,7 @@ class ControlNetPresetUI(object):
|
||||
|
||||
infotext = ControlNetPresetUI.presets[preset_name]
|
||||
preset_unit = parse_unit(infotext)
|
||||
current_unit = external_code.ControlNetUnit(*ui_states)
|
||||
current_unit = init_with_ui_states(*ui_states)
|
||||
preset_unit.image = None
|
||||
current_unit.image = None
|
||||
|
||||
@@ -292,7 +287,7 @@ class ControlNetPresetUI(object):
|
||||
return list(ControlNetPresetUI.presets.keys()) + [NEW_PRESET]
|
||||
|
||||
@staticmethod
|
||||
def save_preset(name: str, unit: external_code.ControlNetUnit):
|
||||
def save_preset(name: str, unit: ControlNetUnit):
|
||||
infotext = serialize_unit(unit)
|
||||
with open(
|
||||
os.path.join(ControlNetPresetUI.preset_directory, f"{name}.txt"), "w"
|
||||
|
||||
@@ -1,5 +1,31 @@
|
||||
from enum import Enum
|
||||
from typing import Any
|
||||
|
||||
|
||||
class HiResFixOption(Enum):
|
||||
BOTH = "Both"
|
||||
LOW_RES_ONLY = "Low res only"
|
||||
HIGH_RES_ONLY = "High res only"
|
||||
|
||||
@staticmethod
|
||||
def from_value(value) -> "HiResFixOption":
|
||||
if isinstance(value, str) and value.startswith("HiResFixOption."):
|
||||
_, field = value.split(".")
|
||||
return getattr(HiResFixOption, field)
|
||||
if isinstance(value, str):
|
||||
return HiResFixOption(value)
|
||||
elif isinstance(value, int):
|
||||
return [x for x in HiResFixOption][value]
|
||||
else:
|
||||
assert isinstance(value, HiResFixOption)
|
||||
return value
|
||||
|
||||
@property
|
||||
def low_res_enabled(self) -> bool:
|
||||
return self in (HiResFixOption.BOTH, HiResFixOption.LOW_RES_ONLY)
|
||||
|
||||
@property
|
||||
def high_res_enabled(self) -> bool:
|
||||
return self in (HiResFixOption.BOTH, HiResFixOption.HIGH_RES_ONLY)
|
||||
|
||||
|
||||
class StableDiffusionVersion(Enum):
|
||||
@@ -43,25 +69,6 @@ class StableDiffusionVersion(Enum):
|
||||
)
|
||||
|
||||
|
||||
class HiResFixOption(Enum):
|
||||
BOTH = "Both"
|
||||
LOW_RES_ONLY = "Low res only"
|
||||
HIGH_RES_ONLY = "High res only"
|
||||
|
||||
@staticmethod
|
||||
def from_value(value: Any) -> "HiResFixOption":
|
||||
if isinstance(value, str) and value.startswith("HiResFixOption."):
|
||||
_, field = value.split(".")
|
||||
return getattr(HiResFixOption, field)
|
||||
if isinstance(value, str):
|
||||
return HiResFixOption(value)
|
||||
elif isinstance(value, int):
|
||||
return [x for x in HiResFixOption][value]
|
||||
else:
|
||||
assert isinstance(value, HiResFixOption)
|
||||
return value
|
||||
|
||||
|
||||
class InputMode(Enum):
|
||||
# Single image to a single ControlNet unit.
|
||||
SIMPLE = "simple"
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
from typing import List, Optional, Union, Tuple, Dict
|
||||
from typing import List, Optional, Union, Dict, TypedDict
|
||||
import numpy as np
|
||||
from modules import shared
|
||||
from lib_controlnet.logging import logger
|
||||
from lib_controlnet.enums import InputMode
|
||||
|
||||
from lib_controlnet.enums import InputMode, HiResFixOption
|
||||
from modules.api import api
|
||||
|
||||
|
||||
@@ -142,33 +141,145 @@ def pixel_perfect_resolution(
|
||||
return int(np.round(estimation))
|
||||
|
||||
|
||||
InputImage = Union[np.ndarray, str]
|
||||
InputImage = Union[Dict[str, InputImage], Tuple[InputImage, InputImage], InputImage]
|
||||
class GradioImageMaskPair(TypedDict):
|
||||
"""Represents the dict object from Gradio's image component if `tool="sketch"`
|
||||
is specified.
|
||||
{
|
||||
"image": np.ndarray,
|
||||
"mask": np.ndarray,
|
||||
}
|
||||
"""
|
||||
image: np.ndarray
|
||||
mask: np.ndarray
|
||||
|
||||
|
||||
@dataclass
|
||||
class UiControlNetUnit:
|
||||
class ControlNetUnit:
|
||||
"""Represents an entire ControlNet processing unit.
|
||||
|
||||
To add a new field to this class
|
||||
## If the new field can be specified on UI, you need to
|
||||
- Add a new field of the same name in constructor of `ControlNetUiGroup`
|
||||
- Initialize the new `ControlNetUiGroup` field in `ControlNetUiGroup.render`
|
||||
as a Gradio `IOComponent`.
|
||||
- Add the new `ControlNetUiGroup` field to `unit_args` in
|
||||
`ControlNetUiGroup.render`. The order of parameters matters.
|
||||
|
||||
## If the new field needs to appear in infotext, you need to
|
||||
- Add a new item in `ControlNetUnit.infotext_fields`.
|
||||
API-only fields cannot appear in infotext.
|
||||
"""
|
||||
# Following fields should only be used in the UI.
|
||||
# ====== Start of UI only fields ======
|
||||
# Specifies the input mode for the unit, defaulting to a simple mode.
|
||||
input_mode: InputMode = InputMode.SIMPLE
|
||||
use_preview_as_input: bool = False,
|
||||
generated_image: Optional[np.ndarray] = None,
|
||||
mask_image: Optional[np.ndarray] = None,
|
||||
# Determines whether to use the preview image as input; defaults to False.
|
||||
use_preview_as_input: bool = False
|
||||
# Directory path for batch processing of images.
|
||||
batch_image_dir: str = ''
|
||||
# Directory path for batch processing of masks.
|
||||
batch_mask_dir: str = ''
|
||||
# Optional list of gallery images for batch input; defaults to None.
|
||||
batch_input_gallery: Optional[List[str]] = None
|
||||
# Optional list of gallery masks for batch processing; defaults to None.
|
||||
batch_mask_gallery: Optional[List[str]] = None
|
||||
# Holds the preview image as a NumPy array; defaults to None.
|
||||
generated_image: Optional[np.ndarray] = None
|
||||
# ====== End of UI only fields ======
|
||||
|
||||
# Following fields are used in both the API and the UI.
|
||||
# Holds the mask image; defaults to None.
|
||||
mask_image: Optional[GradioImageMaskPair] = None
|
||||
# Specifies how this unit should be applied in each pass of high-resolution fix.
|
||||
# Ignored if high-resolution fix is not enabled.
|
||||
hr_option: Union[HiResFixOption, int, str] = HiResFixOption.BOTH
|
||||
# Indicates whether the unit is enabled; defaults to True.
|
||||
enabled: bool = True
|
||||
# Name of the module being used; defaults to "None".
|
||||
module: str = "None"
|
||||
# Name of the model being used; defaults to "None".
|
||||
model: str = "None"
|
||||
# Weight of the unit in the overall processing; defaults to 1.0.
|
||||
weight: float = 1.0
|
||||
image: Optional[Union[InputImage, List[InputImage]]] = None
|
||||
# Optional image for input; defaults to None.
|
||||
image: Optional[GradioImageMaskPair] = None
|
||||
# Specifies the mode of image resizing; defaults to inner fit.
|
||||
resize_mode: Union[ResizeMode, int, str] = ResizeMode.INNER_FIT
|
||||
# Resolution for processing by the unit; defaults to -1 (unspecified).
|
||||
processor_res: int = -1
|
||||
# Threshold A for processing; defaults to -1 (unspecified).
|
||||
threshold_a: float = -1
|
||||
# Threshold B for processing; defaults to -1 (unspecified).
|
||||
threshold_b: float = -1
|
||||
# Start value for guidance; defaults to 0.0.
|
||||
guidance_start: float = 0.0
|
||||
# End value for guidance; defaults to 1.0.
|
||||
guidance_end: float = 1.0
|
||||
# Enables pixel-perfect processing; defaults to False.
|
||||
pixel_perfect: bool = False
|
||||
# Control mode for the unit; defaults to balanced.
|
||||
control_mode: Union[ControlMode, int, str] = ControlMode.BALANCED
|
||||
|
||||
# Following fields should only be used in the API.
|
||||
# ====== Start of API only fields ======
|
||||
# Whether to save the detected map for this unit; defaults to True.
|
||||
save_detected_map: bool = True
|
||||
# ====== End of API only fields ======
|
||||
|
||||
@staticmethod
|
||||
def infotext_fields():
|
||||
"""Fields that should be included in infotext.
|
||||
You should define a Gradio element with exact same name in ControlNetUiGroup
|
||||
as well, so that infotext can wire the value to correct field when pasting
|
||||
infotext.
|
||||
"""
|
||||
return (
|
||||
"module",
|
||||
"model",
|
||||
"weight",
|
||||
"resize_mode",
|
||||
"processor_res",
|
||||
"threshold_a",
|
||||
"threshold_b",
|
||||
"guidance_start",
|
||||
"guidance_end",
|
||||
"pixel_perfect",
|
||||
"control_mode",
|
||||
"hr_option",
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def from_dict(d: Dict) -> "ControlNetUnit":
|
||||
"""Create ControlNetUnit from dict. This is primarily used to convert
|
||||
API json dict to ControlNetUnit."""
|
||||
unit = ControlNetUnit(
|
||||
**{k: v for k, v in d.items() if k in vars(ControlNetUnit)}
|
||||
)
|
||||
if isinstance(unit.image, str):
|
||||
img = np.array(api.decode_base64_to_image(unit.image)).astype('uint8')
|
||||
unit.image = {
|
||||
"image": img,
|
||||
"mask": np.zeros_like(img),
|
||||
}
|
||||
if isinstance(unit.mask_image, str):
|
||||
mask = np.array(api.decode_base64_to_image(unit.mask_image)).astype('uint8')
|
||||
if unit.image is not None:
|
||||
# Attach mask on image if ControlNet has input image.
|
||||
assert isinstance(unit.image, dict)
|
||||
unit.image["mask"] = mask
|
||||
unit.mask_image = None
|
||||
else:
|
||||
# Otherwise, wire to standalone mask.
|
||||
# This happens in img2img when using A1111 img2img input.
|
||||
unit.mask_image = {
|
||||
"image": mask,
|
||||
"mask": np.zeros_like(mask),
|
||||
}
|
||||
return unit
|
||||
|
||||
|
||||
# Backward Compatible
|
||||
ControlNetUnit = UiControlNetUnit
|
||||
UiControlNetUnit = ControlNetUnit
|
||||
|
||||
|
||||
def to_base64_nparray(encoding: str):
|
||||
|
||||
@@ -7,7 +7,7 @@ from lib_controlnet.enums import StableDiffusionVersion
|
||||
from modules_forge.shared import controlnet_dir, supported_preprocessors
|
||||
|
||||
|
||||
CN_MODEL_EXTS = [".pt", ".pth", ".ckpt", ".safetensors", ".bin"]
|
||||
CN_MODEL_EXTS = [".pt", ".pth", ".ckpt", ".safetensors", ".bin", ".patch"]
|
||||
|
||||
|
||||
def traverse_all_files(curr_path, model_list):
|
||||
@@ -98,7 +98,7 @@ def get_filtered_preprocessor_names(tag):
|
||||
return list(get_filtered_preprocessors(tag).keys())
|
||||
|
||||
|
||||
def get_filtered_controlnet_names(tag, filter_version: bool = True):
|
||||
def get_filtered_controlnet_names(tag):
|
||||
filtered_preprocessors = get_filtered_preprocessors(tag)
|
||||
model_filename_filters = []
|
||||
for p in filtered_preprocessors.values():
|
||||
@@ -106,8 +106,8 @@ def get_filtered_controlnet_names(tag, filter_version: bool = True):
|
||||
return [
|
||||
x for x in controlnet_names
|
||||
if x == 'None' or (
|
||||
any(f.lower() in x.lower() for f in model_filename_filters) # and
|
||||
# get_sd_version().is_compatible_with(StableDiffusionVersion.detect_from_model_name(x))
|
||||
any(f.lower() in x.lower() for f in model_filename_filters) and
|
||||
get_sd_version().is_compatible_with(StableDiffusionVersion.detect_from_model_name(x))
|
||||
)
|
||||
]
|
||||
|
||||
@@ -134,6 +134,8 @@ def update_controlnet_filenames():
|
||||
|
||||
|
||||
def get_sd_version() -> StableDiffusionVersion:
|
||||
if not shared.sd_model:
|
||||
return StableDiffusionVersion.UNKNOWN
|
||||
if shared.sd_model.is_sdxl:
|
||||
return StableDiffusionVersion.SDXL
|
||||
elif shared.sd_model.is_sd2:
|
||||
|
||||
@@ -29,19 +29,10 @@ def parse_value(value: str) -> Union[str, float, int, bool]:
|
||||
|
||||
|
||||
def serialize_unit(unit: external_code.ControlNetUnit) -> str:
|
||||
excluded_fields = (
|
||||
"image",
|
||||
"enabled",
|
||||
"input_mode",
|
||||
"use_preview_as_input",
|
||||
"generated_image",
|
||||
"mask_image",
|
||||
)
|
||||
|
||||
log_value = {
|
||||
field_to_displaytext(field): getattr(unit, field)
|
||||
for field in vars(external_code.ControlNetUnit()).keys()
|
||||
if field not in excluded_fields and getattr(unit, field) != -1
|
||||
for field in external_code.ControlNetUnit.infotext_fields()
|
||||
if getattr(unit, field) != -1
|
||||
# Note: exclude hidden slider values.
|
||||
}
|
||||
if not all("," not in str(v) and ":" not in str(v) for v in log_value.values()):
|
||||
@@ -81,12 +72,8 @@ class Infotext(object):
|
||||
iocomponents.
|
||||
"""
|
||||
unit_prefix = Infotext.unit_prefix(unit_index)
|
||||
for field in vars(external_code.ControlNetUnit()).keys():
|
||||
# Exclude image for infotext.
|
||||
if field == "image":
|
||||
continue
|
||||
|
||||
# Every field in ControlNetUnit should have a cooresponding
|
||||
for field in external_code.ControlNetUnit.infotext_fields():
|
||||
# Every field in ControlNetUnit should have a corresponding
|
||||
# IOComponent in ControlNetUiGroup.
|
||||
io_component = getattr(uigroup, field)
|
||||
component_locator = f"{unit_prefix} {field}"
|
||||
|
||||
@@ -190,44 +190,6 @@ def align_dim_latent(x: int) -> int:
|
||||
return (x // 8) * 8
|
||||
|
||||
|
||||
def image_dict_from_any(image) -> Optional[Dict[str, np.ndarray]]:
|
||||
if image is None:
|
||||
return None
|
||||
|
||||
if isinstance(image, (tuple, list)):
|
||||
image = {'image': image[0], 'mask': image[1]}
|
||||
elif not isinstance(image, dict):
|
||||
image = {'image': image, 'mask': None}
|
||||
else: # type(image) is dict
|
||||
# copy to enable modifying the dict and prevent response serialization error
|
||||
image = dict(image)
|
||||
|
||||
if isinstance(image['image'], str):
|
||||
if os.path.exists(image['image']):
|
||||
image['image'] = np.array(Image.open(image['image'])).astype('uint8')
|
||||
elif image['image']:
|
||||
image['image'] = external_code.to_base64_nparray(image['image'])
|
||||
else:
|
||||
image['image'] = None
|
||||
|
||||
# If there is no image, return image with None image and None mask
|
||||
if image['image'] is None:
|
||||
image['mask'] = None
|
||||
return image
|
||||
|
||||
if 'mask' not in image or image['mask'] is None:
|
||||
image['mask'] = np.zeros_like(image['image'], dtype=np.uint8)
|
||||
elif isinstance(image['mask'], str):
|
||||
if os.path.exists(image['mask']):
|
||||
image['mask'] = np.array(Image.open(image['mask'])).astype('uint8')
|
||||
elif image['mask']:
|
||||
image['mask'] = external_code.to_base64_nparray(image['mask'])
|
||||
else:
|
||||
image['mask'] = np.zeros_like(image['image'], dtype=np.uint8)
|
||||
|
||||
return image
|
||||
|
||||
|
||||
def prepare_mask(
|
||||
mask: Image.Image, p: processing.StableDiffusionProcessing
|
||||
) -> Image.Image:
|
||||
|
||||
@@ -11,15 +11,18 @@ from modules.api.api import decode_base64_to_image
|
||||
import gradio as gr
|
||||
|
||||
from lib_controlnet import global_state, external_code
|
||||
from lib_controlnet.utils import align_dim_latent, image_dict_from_any, set_numpy_seed, crop_and_resize_image, \
|
||||
from lib_controlnet.external_code import ControlNetUnit
|
||||
from lib_controlnet.utils import align_dim_latent, set_numpy_seed, crop_and_resize_image, \
|
||||
prepare_mask, judge_image_type
|
||||
from lib_controlnet.controlnet_ui.controlnet_ui_group import ControlNetUiGroup, UiControlNetUnit
|
||||
from lib_controlnet.controlnet_ui.controlnet_ui_group import ControlNetUiGroup
|
||||
from lib_controlnet.controlnet_ui.photopea import Photopea
|
||||
from lib_controlnet.logging import logger
|
||||
from modules.processing import StableDiffusionProcessingImg2Img, StableDiffusionProcessingTxt2Img, \
|
||||
StableDiffusionProcessing
|
||||
from lib_controlnet.infotext import Infotext
|
||||
from modules_forge.forge_util import HWC3, numpy_to_pytorch
|
||||
from lib_controlnet.enums import HiResFixOption
|
||||
from lib_controlnet.api import controlnet_api
|
||||
|
||||
import numpy as np
|
||||
import functools
|
||||
@@ -53,6 +56,8 @@ class ControlNetCachedParameters:
|
||||
|
||||
|
||||
class ControlNetForForgeOfficial(scripts.Script):
|
||||
sorting_priority = 10
|
||||
|
||||
def title(self):
|
||||
return "ControlNet"
|
||||
|
||||
@@ -66,7 +71,7 @@ class ControlNetForForgeOfficial(scripts.Script):
|
||||
max_models = shared.opts.data.get("control_net_unit_count", 3)
|
||||
gen_type = "img2img" if is_img2img else "txt2img"
|
||||
elem_id_tabname = gen_type + "_controlnet"
|
||||
default_unit = UiControlNetUnit(enabled=False, module="None", model="None")
|
||||
default_unit = ControlNetUnit(enabled=False, module="None", model="None")
|
||||
with gr.Group(elem_id=elem_id_tabname):
|
||||
with gr.Accordion(f"ControlNet Integrated", open=False, elem_id="controlnet",
|
||||
elem_classes=["controlnet"]):
|
||||
@@ -94,13 +99,19 @@ class ControlNetForForgeOfficial(scripts.Script):
|
||||
return tuple(controls)
|
||||
|
||||
def get_enabled_units(self, units):
|
||||
# Parse dict from API calls.
|
||||
units = [
|
||||
ControlNetUnit.from_dict(unit) if isinstance(unit, dict) else unit
|
||||
for unit in units
|
||||
]
|
||||
assert all(isinstance(unit, ControlNetUnit) for unit in units)
|
||||
enabled_units = [x for x in units if x.enabled]
|
||||
return enabled_units
|
||||
|
||||
@staticmethod
|
||||
def try_crop_image_with_a1111_mask(
|
||||
p: StableDiffusionProcessing,
|
||||
unit: external_code.ControlNetUnit,
|
||||
unit: ControlNetUnit,
|
||||
input_image: np.ndarray,
|
||||
resize_mode: external_code.ResizeMode,
|
||||
preprocessor
|
||||
@@ -139,48 +150,107 @@ class ControlNetForForgeOfficial(scripts.Script):
|
||||
input_image = np.stack(input_image, axis=2)
|
||||
return input_image
|
||||
|
||||
def get_input_data(self, p, unit, preprocessor):
|
||||
a1111_i2i_image = getattr(p, "init_images", [None])[0]
|
||||
a1111_i2i_mask = getattr(p, "image_mask", None)
|
||||
|
||||
using_a1111_data = False
|
||||
|
||||
def get_input_data(self, p, unit, preprocessor, h, w):
|
||||
logger.info(f'ControlNet Input Mode: {unit.input_mode}')
|
||||
image_list = []
|
||||
resize_mode = external_code.resize_mode_from_value(unit.resize_mode)
|
||||
|
||||
if unit.use_preview_as_input and unit.generated_image is not None:
|
||||
image = unit.generated_image
|
||||
elif unit.image is None:
|
||||
resize_mode = external_code.resize_mode_from_value(p.resize_mode)
|
||||
image = HWC3(np.asarray(a1111_i2i_image))
|
||||
using_a1111_data = True
|
||||
elif (unit.image['image'] < 5).all() and (unit.image['mask'] > 5).any():
|
||||
image = unit.image['mask']
|
||||
if unit.input_mode == external_code.InputMode.MERGE:
|
||||
for idx, item in enumerate(unit.batch_input_gallery):
|
||||
img_path = item['name']
|
||||
logger.info(f'Try to read image: {img_path}')
|
||||
img = np.ascontiguousarray(cv2.imread(img_path)[:, :, ::-1]).copy()
|
||||
mask = None
|
||||
if len(unit.batch_mask_gallery) > 0:
|
||||
if len(unit.batch_mask_gallery) >= len(unit.batch_input_gallery):
|
||||
mask_path = unit.batch_mask_gallery[idx]['name']
|
||||
else:
|
||||
mask_path = unit.batch_mask_gallery[0]['name']
|
||||
mask = np.ascontiguousarray(cv2.imread(mask_path)[:, :, ::-1]).copy()
|
||||
if img is not None:
|
||||
image_list.append([img, mask])
|
||||
elif unit.input_mode == external_code.InputMode.BATCH:
|
||||
image_list = []
|
||||
image_extensions = ['.jpg', '.jpeg', '.png', '.bmp']
|
||||
batch_image_files = shared.listfiles(unit.batch_image_dir)
|
||||
for batch_modifier in getattr(unit, 'batch_modifiers', []):
|
||||
batch_image_files = batch_modifier(batch_image_files, p)
|
||||
for idx, filename in enumerate(batch_image_files):
|
||||
if any(filename.lower().endswith(ext) for ext in image_extensions):
|
||||
img_path = os.path.join(unit.batch_image_dir, filename)
|
||||
logger.info(f'Try to read image: {img_path}')
|
||||
img = np.ascontiguousarray(cv2.imread(img_path)[:, :, ::-1]).copy()
|
||||
mask = None
|
||||
if unit.batch_mask_dir:
|
||||
batch_mask_files = shared.listfiles(unit.batch_mask_dir)
|
||||
if len(batch_mask_files) >= len(batch_image_files):
|
||||
mask_path = batch_mask_files[idx]
|
||||
else:
|
||||
mask_path = batch_mask_files[0]
|
||||
mask_path = os.path.join(unit.batch_mask_dir, mask_path)
|
||||
mask = np.ascontiguousarray(cv2.imread(mask_path)[:, :, ::-1]).copy()
|
||||
if img is not None:
|
||||
image_list.append([img, mask])
|
||||
else:
|
||||
image = unit.image['image']
|
||||
a1111_i2i_image = getattr(p, "init_images", [None])[0]
|
||||
a1111_i2i_mask = getattr(p, "image_mask", None)
|
||||
|
||||
if not isinstance(image, np.ndarray):
|
||||
raise ValueError("controlnet is enabled but no input image is given")
|
||||
using_a1111_data = False
|
||||
|
||||
image = HWC3(image)
|
||||
if unit.use_preview_as_input and unit.generated_image is not None:
|
||||
image = unit.generated_image
|
||||
elif unit.image is None:
|
||||
resize_mode = external_code.resize_mode_from_value(p.resize_mode)
|
||||
image = HWC3(np.asarray(a1111_i2i_image))
|
||||
using_a1111_data = True
|
||||
elif (unit.image['image'] < 5).all() and (unit.image['mask'] > 5).any():
|
||||
image = unit.image['mask']
|
||||
else:
|
||||
image = unit.image['image']
|
||||
|
||||
if using_a1111_data:
|
||||
mask = HWC3(np.asarray(a1111_i2i_mask))
|
||||
elif unit.mask_image is not None and (unit.mask_image['image'] > 5).any():
|
||||
mask = unit.mask_image['image']
|
||||
elif unit.mask_image is not None and (unit.mask_image['mask'] > 5).any():
|
||||
mask = unit.mask_image['mask']
|
||||
elif unit.image is not None and (unit.image['mask'] > 5).any():
|
||||
mask = unit.image['mask']
|
||||
else:
|
||||
mask = None
|
||||
if not isinstance(image, np.ndarray):
|
||||
raise ValueError("controlnet is enabled but no input image is given")
|
||||
|
||||
image = self.try_crop_image_with_a1111_mask(p, unit, image, resize_mode, preprocessor)
|
||||
image = HWC3(image)
|
||||
|
||||
if mask is not None:
|
||||
mask = cv2.resize(HWC3(mask), (image.shape[1], image.shape[0]), interpolation=cv2.INTER_NEAREST)
|
||||
mask = self.try_crop_image_with_a1111_mask(p, unit, mask, resize_mode, preprocessor)
|
||||
if using_a1111_data:
|
||||
mask = HWC3(np.asarray(a1111_i2i_mask)) if a1111_i2i_mask is not None else None
|
||||
elif unit.mask_image is not None and (unit.mask_image['image'] > 5).any():
|
||||
mask = unit.mask_image['image']
|
||||
elif unit.mask_image is not None and (unit.mask_image['mask'] > 5).any():
|
||||
mask = unit.mask_image['mask']
|
||||
elif unit.image is not None and (unit.image['mask'] > 5).any():
|
||||
mask = unit.image['mask']
|
||||
else:
|
||||
mask = None
|
||||
|
||||
return image, mask, resize_mode
|
||||
image = self.try_crop_image_with_a1111_mask(p, unit, image, resize_mode, preprocessor)
|
||||
|
||||
if mask is not None:
|
||||
mask = cv2.resize(HWC3(mask), (image.shape[1], image.shape[0]), interpolation=cv2.INTER_NEAREST)
|
||||
mask = self.try_crop_image_with_a1111_mask(p, unit, mask, resize_mode, preprocessor)
|
||||
|
||||
image_list = [[image, mask]]
|
||||
|
||||
if resize_mode == external_code.ResizeMode.OUTER_FIT and preprocessor.expand_mask_when_resize_and_fill:
|
||||
new_image_list = []
|
||||
for input_image, input_mask in image_list:
|
||||
if input_mask is None:
|
||||
input_mask = np.zeros_like(input_image)
|
||||
input_mask = crop_and_resize_image(
|
||||
input_mask,
|
||||
external_code.ResizeMode.OUTER_FIT, h, w,
|
||||
fill_border_with_255=True,
|
||||
)
|
||||
input_image = crop_and_resize_image(
|
||||
input_image,
|
||||
external_code.ResizeMode.OUTER_FIT, h, w,
|
||||
fill_border_with_255=False,
|
||||
)
|
||||
new_image_list.append((input_image, input_mask))
|
||||
image_list = new_image_list
|
||||
|
||||
return image_list, resize_mode
|
||||
|
||||
@staticmethod
|
||||
def get_target_dimensions(p: StableDiffusionProcessing) -> Tuple[int, int, int, int]:
|
||||
@@ -209,7 +279,7 @@ class ControlNetForForgeOfficial(scripts.Script):
|
||||
@torch.no_grad()
|
||||
def process_unit_after_click_generate(self,
|
||||
p: StableDiffusionProcessing,
|
||||
unit: external_code.ControlNetUnit,
|
||||
unit: ControlNetUnit,
|
||||
params: ControlNetCachedParameters,
|
||||
*args, **kwargs):
|
||||
|
||||
@@ -225,58 +295,106 @@ class ControlNetForForgeOfficial(scripts.Script):
|
||||
|
||||
preprocessor = global_state.get_preprocessor(unit.module)
|
||||
|
||||
input_image, input_mask, resize_mode = self.get_input_data(p, unit, preprocessor)
|
||||
# p.extra_result_images.append(input_image)
|
||||
input_list, resize_mode = self.get_input_data(p, unit, preprocessor, h, w)
|
||||
preprocessor_outputs = []
|
||||
control_masks = []
|
||||
preprocessor_output_is_image = False
|
||||
preprocessor_output = None
|
||||
|
||||
if unit.pixel_perfect:
|
||||
unit.processor_res = external_code.pixel_perfect_resolution(
|
||||
input_image,
|
||||
target_H=h,
|
||||
target_W=w,
|
||||
resize_mode=resize_mode,
|
||||
def optional_tqdm(iterable, use_tqdm):
|
||||
from tqdm import tqdm
|
||||
return tqdm(iterable) if use_tqdm else iterable
|
||||
|
||||
for input_image, input_mask in optional_tqdm(input_list, len(input_list) > 1):
|
||||
if unit.pixel_perfect:
|
||||
unit.processor_res = external_code.pixel_perfect_resolution(
|
||||
input_image,
|
||||
target_H=h,
|
||||
target_W=w,
|
||||
resize_mode=resize_mode,
|
||||
)
|
||||
|
||||
seed = set_numpy_seed(p)
|
||||
logger.debug(f"Use numpy seed {seed}.")
|
||||
logger.info(f"Using preprocessor: {unit.module}")
|
||||
logger.info(f'preprocessor resolution = {unit.processor_res}')
|
||||
|
||||
preprocessor_output = preprocessor(
|
||||
input_image=input_image,
|
||||
input_mask=input_mask,
|
||||
resolution=unit.processor_res,
|
||||
slider_1=unit.threshold_a,
|
||||
slider_2=unit.threshold_b,
|
||||
)
|
||||
|
||||
seed = set_numpy_seed(p)
|
||||
logger.debug(f"Use numpy seed {seed}.")
|
||||
logger.info(f"Using preprocessor: {unit.module}")
|
||||
logger.info(f'preprocessor resolution = {unit.processor_res}')
|
||||
preprocessor_outputs.append(preprocessor_output)
|
||||
|
||||
preprocessor_output = preprocessor(
|
||||
input_image=input_image,
|
||||
input_mask=input_mask,
|
||||
resolution=unit.processor_res,
|
||||
slider_1=unit.threshold_a,
|
||||
slider_2=unit.threshold_b,
|
||||
)
|
||||
preprocessor_output_is_image = judge_image_type(preprocessor_output)
|
||||
|
||||
preprocessor_output_is_image = judge_image_type(preprocessor_output)
|
||||
if input_mask is not None:
|
||||
control_masks.append(input_mask)
|
||||
|
||||
if len(input_list) > 1 and not preprocessor_output_is_image:
|
||||
logger.info('Batch wise input only support controlnet, control-lora, and t2i adapters!')
|
||||
break
|
||||
|
||||
if has_high_res_fix:
|
||||
hr_option = HiResFixOption.from_value(unit.hr_option)
|
||||
else:
|
||||
hr_option = HiResFixOption.BOTH
|
||||
|
||||
alignment_indices = [i % len(preprocessor_outputs) for i in range(p.batch_size)]
|
||||
def attach_extra_result_image(img: np.ndarray, is_high_res: bool = False):
|
||||
if (
|
||||
(is_high_res and hr_option.high_res_enabled) or
|
||||
(not is_high_res and hr_option.low_res_enabled)
|
||||
) and unit.save_detected_map:
|
||||
p.extra_result_images.append(img)
|
||||
|
||||
if preprocessor_output_is_image:
|
||||
params.control_cond = crop_and_resize_image(preprocessor_output, resize_mode, h, w)
|
||||
p.extra_result_images.append(external_code.visualize_inpaint_mask(params.control_cond))
|
||||
params.control_cond = numpy_to_pytorch(params.control_cond).movedim(-1, 1)
|
||||
params.control_cond = []
|
||||
params.control_cond_for_hr_fix = []
|
||||
|
||||
for preprocessor_output in preprocessor_outputs:
|
||||
control_cond = crop_and_resize_image(preprocessor_output, resize_mode, h, w)
|
||||
attach_extra_result_image(external_code.visualize_inpaint_mask(control_cond))
|
||||
params.control_cond.append(numpy_to_pytorch(control_cond).movedim(-1, 1))
|
||||
|
||||
params.control_cond = torch.cat(params.control_cond, dim=0)[alignment_indices].contiguous()
|
||||
|
||||
if has_high_res_fix:
|
||||
params.control_cond_for_hr_fix = crop_and_resize_image(preprocessor_output, resize_mode, hr_y, hr_x)
|
||||
p.extra_result_images.append(external_code.visualize_inpaint_mask(params.control_cond_for_hr_fix))
|
||||
params.control_cond_for_hr_fix = numpy_to_pytorch(params.control_cond_for_hr_fix).movedim(-1, 1)
|
||||
for preprocessor_output in preprocessor_outputs:
|
||||
control_cond_for_hr_fix = crop_and_resize_image(preprocessor_output, resize_mode, hr_y, hr_x)
|
||||
attach_extra_result_image(external_code.visualize_inpaint_mask(control_cond_for_hr_fix), is_high_res=True)
|
||||
params.control_cond_for_hr_fix.append(numpy_to_pytorch(control_cond_for_hr_fix).movedim(-1, 1))
|
||||
params.control_cond_for_hr_fix = torch.cat(params.control_cond_for_hr_fix, dim=0)[alignment_indices].contiguous()
|
||||
else:
|
||||
params.control_cond_for_hr_fix = params.control_cond
|
||||
else:
|
||||
params.control_cond = preprocessor_output
|
||||
params.control_cond_for_hr_fix = preprocessor_output
|
||||
p.extra_result_images.append(input_image)
|
||||
attach_extra_result_image(input_image)
|
||||
|
||||
if input_mask is not None:
|
||||
fill_border = preprocessor.fill_mask_with_one_when_resize_and_fill
|
||||
params.control_mask = crop_and_resize_image(input_mask, resize_mode, h, w, fill_border)
|
||||
p.extra_result_images.append(params.control_mask)
|
||||
params.control_mask = numpy_to_pytorch(params.control_mask).movedim(-1, 1)[:, :1]
|
||||
if len(control_masks) > 0:
|
||||
params.control_mask = []
|
||||
params.control_mask_for_hr_fix = []
|
||||
|
||||
for input_mask in control_masks:
|
||||
fill_border = preprocessor.fill_mask_with_one_when_resize_and_fill
|
||||
control_mask = crop_and_resize_image(input_mask, resize_mode, h, w, fill_border)
|
||||
attach_extra_result_image(control_mask)
|
||||
control_mask = numpy_to_pytorch(control_mask).movedim(-1, 1)[:, :1]
|
||||
params.control_mask.append(control_mask)
|
||||
|
||||
if has_high_res_fix:
|
||||
control_mask_for_hr_fix = crop_and_resize_image(input_mask, resize_mode, hr_y, hr_x, fill_border)
|
||||
attach_extra_result_image(control_mask_for_hr_fix, is_high_res=True)
|
||||
control_mask_for_hr_fix = numpy_to_pytorch(control_mask_for_hr_fix).movedim(-1, 1)[:, :1]
|
||||
params.control_mask_for_hr_fix.append(control_mask_for_hr_fix)
|
||||
|
||||
params.control_mask = torch.cat(params.control_mask, dim=0)[alignment_indices].contiguous()
|
||||
if has_high_res_fix:
|
||||
params.control_mask_for_hr_fix = crop_and_resize_image(input_mask, resize_mode, hr_y, hr_x, fill_border)
|
||||
p.extra_result_images.append(params.control_mask_for_hr_fix)
|
||||
params.control_mask_for_hr_fix = numpy_to_pytorch(params.control_mask_for_hr_fix).movedim(-1, 1)[:, :1]
|
||||
params.control_mask_for_hr_fix = torch.cat(params.control_mask_for_hr_fix, dim=0)[alignment_indices].contiguous()
|
||||
else:
|
||||
params.control_mask_for_hr_fix = params.control_mask
|
||||
|
||||
@@ -300,12 +418,30 @@ class ControlNetForForgeOfficial(scripts.Script):
|
||||
@torch.no_grad()
|
||||
def process_unit_before_every_sampling(self,
|
||||
p: StableDiffusionProcessing,
|
||||
unit: external_code.ControlNetUnit,
|
||||
unit: ControlNetUnit,
|
||||
params: ControlNetCachedParameters,
|
||||
*args, **kwargs):
|
||||
|
||||
is_hr_pass = getattr(p, 'is_hr_pass', False)
|
||||
|
||||
has_high_res_fix = (
|
||||
isinstance(p, StableDiffusionProcessingTxt2Img)
|
||||
and getattr(p, 'enable_hr', False)
|
||||
)
|
||||
|
||||
if has_high_res_fix:
|
||||
hr_option = HiResFixOption.from_value(unit.hr_option)
|
||||
else:
|
||||
hr_option = HiResFixOption.BOTH
|
||||
|
||||
if has_high_res_fix and is_hr_pass and (not hr_option.high_res_enabled):
|
||||
logger.info(f"ControlNet Skipped High-res pass.")
|
||||
return
|
||||
|
||||
if has_high_res_fix and (not is_hr_pass) and (not hr_option.low_res_enabled):
|
||||
logger.info(f"ControlNet Skipped Low-res pass.")
|
||||
return
|
||||
|
||||
if is_hr_pass:
|
||||
cond = params.control_cond_for_hr_fix
|
||||
mask = params.control_mask_for_hr_fix
|
||||
@@ -313,7 +449,12 @@ class ControlNetForForgeOfficial(scripts.Script):
|
||||
cond = params.control_cond
|
||||
mask = params.control_mask
|
||||
|
||||
kwargs.update(dict(unit=unit, params=params))
|
||||
kwargs.update(dict(
|
||||
unit=unit,
|
||||
params=params,
|
||||
cond_original=cond.clone() if isinstance(cond, torch.Tensor) else cond,
|
||||
mask_original=mask.clone() if isinstance(mask, torch.Tensor) else mask,
|
||||
))
|
||||
|
||||
params.model.strength = float(unit.weight)
|
||||
params.model.start_percent = float(unit.guidance_start)
|
||||
@@ -328,7 +469,7 @@ class ControlNetForForgeOfficial(scripts.Script):
|
||||
0.214600924414215,
|
||||
0.26012233262329093, 0.3152997971191405, 0.3821815722656249, 0.4632503906249999, 0.561515625,
|
||||
0.6806249999999999, 0.825],
|
||||
'middle': [1.0],
|
||||
'middle': [0.561515625] if p.sd_model.is_sdxl else [1.0],
|
||||
'output': [0.09941396206337118, 0.12050177219802567, 0.14606275417942507, 0.17704576264172736,
|
||||
0.214600924414215,
|
||||
0.26012233262329093, 0.3152997971191405, 0.3821815722656249, 0.4632503906249999, 0.561515625,
|
||||
@@ -345,8 +486,11 @@ class ControlNetForForgeOfficial(scripts.Script):
|
||||
params.model.positive_advanced_weighting = soft_weighting.copy()
|
||||
params.model.negative_advanced_weighting = zero_weighting.copy()
|
||||
|
||||
# high-ref fix pass always use softer injections
|
||||
if is_hr_pass or unit.control_mode == external_code.ControlMode.PROMPT.value:
|
||||
if unit.control_mode == external_code.ControlMode.PROMPT.value:
|
||||
params.model.positive_advanced_weighting = soft_weighting.copy()
|
||||
params.model.negative_advanced_weighting = soft_weighting.copy()
|
||||
|
||||
if is_hr_pass and params.preprocessor.use_soft_projection_in_hr_fix:
|
||||
params.model.positive_advanced_weighting = soft_weighting.copy()
|
||||
params.model.negative_advanced_weighting = soft_weighting.copy()
|
||||
|
||||
@@ -360,14 +504,14 @@ class ControlNetForForgeOfficial(scripts.Script):
|
||||
return
|
||||
|
||||
@staticmethod
|
||||
def bound_check_params(unit: external_code.ControlNetUnit) -> None:
|
||||
def bound_check_params(unit: ControlNetUnit) -> None:
|
||||
"""
|
||||
Checks and corrects negative parameters in ControlNetUnit 'unit'.
|
||||
Parameters 'processor_res', 'threshold_a', 'threshold_b' are reset to
|
||||
their default values if negative.
|
||||
|
||||
Args:
|
||||
unit (external_code.ControlNetUnit): The ControlNetUnit instance to check.
|
||||
unit (ControlNetUnit): The ControlNetUnit instance to check.
|
||||
"""
|
||||
preprocessor = global_state.get_preprocessor(unit.module)
|
||||
|
||||
@@ -385,7 +529,7 @@ class ControlNetForForgeOfficial(scripts.Script):
|
||||
@torch.no_grad()
|
||||
def process_unit_after_every_sampling(self,
|
||||
p: StableDiffusionProcessing,
|
||||
unit: external_code.ControlNetUnit,
|
||||
unit: ControlNetUnit,
|
||||
params: ControlNetCachedParameters,
|
||||
*args, **kwargs):
|
||||
|
||||
@@ -415,6 +559,9 @@ class ControlNetForForgeOfficial(scripts.Script):
|
||||
def postprocess_batch_list(self, p, pp, *args, **kwargs):
|
||||
for i, unit in enumerate(self.get_enabled_units(args)):
|
||||
self.process_unit_after_every_sampling(p, unit, self.current_params[i], pp, *args, **kwargs)
|
||||
return
|
||||
|
||||
def postprocess(self, p, processed, *args):
|
||||
self.current_params = {}
|
||||
return
|
||||
|
||||
@@ -461,3 +608,4 @@ script_callbacks.on_ui_settings(on_ui_settings)
|
||||
script_callbacks.on_infotext_pasted(Infotext.on_infotext_pasted)
|
||||
script_callbacks.on_after_component(ControlNetUiGroup.on_after_component)
|
||||
script_callbacks.on_before_reload(ControlNetUiGroup.reset)
|
||||
script_callbacks.on_app_started(controlnet_api)
|
||||
|
||||
7
extensions-builtin/sd_forge_controlnet/tests/conftest.py
Normal file
@@ -0,0 +1,7 @@
|
||||
import os
|
||||
|
||||
|
||||
def pytest_configure(config):
|
||||
# We don't want to fail on Py.test command line arguments being
|
||||
# parsed by webui:
|
||||
os.environ.setdefault("IGNORE_CMD_ARGS_ERRORS", "1")
|
||||
BIN
extensions-builtin/sd_forge_controlnet/tests/images/1girl.png
Normal file
|
After Width: | Height: | Size: 482 KiB |
BIN
extensions-builtin/sd_forge_controlnet/tests/images/mask.png
Normal file
|
After Width: | Height: | Size: 244 B |
|
After Width: | Height: | Size: 226 B |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 37 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 6.4 KiB |
|
After Width: | Height: | Size: 202 KiB |
|
After Width: | Height: | Size: 15 KiB |
@@ -0,0 +1,63 @@
|
||||
import pytest
|
||||
import requests
|
||||
from typing import List
|
||||
|
||||
from .template import (
|
||||
APITestTemplate,
|
||||
realistic_girl_face_img,
|
||||
save_base64,
|
||||
get_dest_dir,
|
||||
disable_in_cq,
|
||||
)
|
||||
|
||||
|
||||
def get_modules() -> List[str]:
|
||||
return requests.get(APITestTemplate.BASE_URL + "controlnet/module_list").json()[
|
||||
"module_list"
|
||||
]
|
||||
|
||||
|
||||
def detect_template(payload, output_name: str):
|
||||
url = APITestTemplate.BASE_URL + "controlnet/detect"
|
||||
resp = requests.post(url, json=payload)
|
||||
assert resp.status_code == 200
|
||||
resp_json = resp.json()
|
||||
assert "images" in resp_json
|
||||
assert len(resp_json["images"]) == len(payload["controlnet_input_images"])
|
||||
if not APITestTemplate.is_cq_run:
|
||||
for i, img in enumerate(resp_json["images"]):
|
||||
if img == "Detect result is not image":
|
||||
continue
|
||||
dest = get_dest_dir() / f"{output_name}_{i}.png"
|
||||
save_base64(img, dest)
|
||||
return resp_json
|
||||
|
||||
|
||||
@disable_in_cq
|
||||
@pytest.mark.parametrize("module", get_modules())
|
||||
def test_detect_all_modules(module: str):
|
||||
payload = dict(
|
||||
controlnet_input_images=[realistic_girl_face_img],
|
||||
controlnet_module=module,
|
||||
)
|
||||
detect_template(payload, f"detect_{module}")
|
||||
|
||||
|
||||
def test_detect_simple():
|
||||
detect_template(
|
||||
dict(
|
||||
controlnet_input_images=[realistic_girl_face_img],
|
||||
controlnet_module="canny", # Canny does not require model download.
|
||||
),
|
||||
"simple_detect",
|
||||
)
|
||||
|
||||
|
||||
def test_detect_multiple_inputs():
|
||||
detect_template(
|
||||
dict(
|
||||
controlnet_input_images=[realistic_girl_face_img, realistic_girl_face_img],
|
||||
controlnet_module="canny", # Canny does not require model download.
|
||||
),
|
||||
"multiple_inputs_detect",
|
||||
)
|
||||
@@ -0,0 +1,171 @@
|
||||
import pytest
|
||||
|
||||
from .template import (
|
||||
APITestTemplate,
|
||||
girl_img,
|
||||
mask_img,
|
||||
disable_in_cq,
|
||||
get_model,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("gen_type", ["img2img", "txt2img"])
|
||||
def test_no_unit(gen_type):
|
||||
assert APITestTemplate(
|
||||
f"test_no_unit{gen_type}",
|
||||
gen_type,
|
||||
payload_overrides={},
|
||||
unit_overrides=[],
|
||||
input_image=girl_img,
|
||||
).exec()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("gen_type", ["img2img", "txt2img"])
|
||||
def test_multiple_iter(gen_type):
|
||||
assert APITestTemplate(
|
||||
f"test_multiple_iter{gen_type}",
|
||||
gen_type,
|
||||
payload_overrides={"n_iter": 2},
|
||||
unit_overrides={},
|
||||
input_image=girl_img,
|
||||
).exec()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("gen_type", ["img2img", "txt2img"])
|
||||
def test_batch_size(gen_type):
|
||||
assert APITestTemplate(
|
||||
f"test_batch_size{gen_type}",
|
||||
gen_type,
|
||||
payload_overrides={"batch_size": 2},
|
||||
unit_overrides={},
|
||||
input_image=girl_img,
|
||||
).exec()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("gen_type", ["img2img", "txt2img"])
|
||||
def test_2_units(gen_type):
|
||||
assert APITestTemplate(
|
||||
f"test_2_units{gen_type}",
|
||||
gen_type,
|
||||
payload_overrides={},
|
||||
unit_overrides=[{}, {}],
|
||||
input_image=girl_img,
|
||||
).exec()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("gen_type", ["img2img", "txt2img"])
|
||||
def test_preprocessor(gen_type):
|
||||
assert APITestTemplate(
|
||||
f"test_preprocessor{gen_type}",
|
||||
gen_type,
|
||||
payload_overrides={},
|
||||
unit_overrides={"module": "canny"},
|
||||
input_image=girl_img,
|
||||
).exec()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("param_name", ("processor_res", "threshold_a", "threshold_b"))
|
||||
@pytest.mark.parametrize("gen_type", ["img2img", "txt2img"])
|
||||
def test_invalid_param(gen_type, param_name):
|
||||
assert APITestTemplate(
|
||||
f"test_invalid_param{(gen_type, param_name)}",
|
||||
gen_type,
|
||||
payload_overrides={},
|
||||
unit_overrides={param_name: -1},
|
||||
input_image=girl_img,
|
||||
).exec()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("save_map", [True, False])
|
||||
@pytest.mark.parametrize("gen_type", ["img2img", "txt2img"])
|
||||
def test_save_map(gen_type, save_map):
|
||||
assert APITestTemplate(
|
||||
f"test_save_map{(gen_type, save_map)}",
|
||||
gen_type,
|
||||
payload_overrides={},
|
||||
unit_overrides={"save_detected_map": save_map},
|
||||
input_image=girl_img,
|
||||
).exec(expected_output_num=2 if save_map else 1)
|
||||
|
||||
|
||||
@disable_in_cq
|
||||
def test_masked_controlnet_txt2img():
|
||||
assert APITestTemplate(
|
||||
f"test_masked_controlnet_txt2img",
|
||||
"txt2img",
|
||||
payload_overrides={},
|
||||
unit_overrides={
|
||||
"image": girl_img,
|
||||
"mask_image": mask_img,
|
||||
},
|
||||
).exec()
|
||||
|
||||
|
||||
@disable_in_cq
|
||||
def test_masked_controlnet_img2img():
|
||||
assert APITestTemplate(
|
||||
f"test_masked_controlnet_img2img",
|
||||
"img2img",
|
||||
payload_overrides={
|
||||
"init_images": [girl_img],
|
||||
},
|
||||
# Note: Currently you must give ControlNet unit input image to specify
|
||||
# mask.
|
||||
# TODO: Fix this for img2img.
|
||||
unit_overrides={
|
||||
"image": girl_img,
|
||||
"mask_image": mask_img,
|
||||
},
|
||||
).exec()
|
||||
|
||||
|
||||
@disable_in_cq
|
||||
def test_txt2img_inpaint():
|
||||
assert APITestTemplate(
|
||||
"txt2img_inpaint",
|
||||
"txt2img",
|
||||
payload_overrides={},
|
||||
unit_overrides={
|
||||
"image": girl_img,
|
||||
"mask_image": mask_img,
|
||||
"model": get_model("v11p_sd15_inpaint"),
|
||||
"module": "inpaint_only",
|
||||
},
|
||||
).exec()
|
||||
|
||||
|
||||
@disable_in_cq
|
||||
def test_img2img_inpaint():
|
||||
assert APITestTemplate(
|
||||
"img2img_inpaint",
|
||||
"img2img",
|
||||
payload_overrides={
|
||||
"init_images": [girl_img],
|
||||
"mask": mask_img,
|
||||
},
|
||||
unit_overrides={
|
||||
"model": get_model("v11p_sd15_inpaint"),
|
||||
"module": "inpaint_only",
|
||||
},
|
||||
).exec()
|
||||
|
||||
|
||||
# Currently failing.
|
||||
# TODO Fix lama outpaint.
|
||||
@disable_in_cq
|
||||
def test_lama_outpaint():
|
||||
assert APITestTemplate(
|
||||
"txt2img_lama_outpaint",
|
||||
"txt2img",
|
||||
payload_overrides={
|
||||
"width": 768,
|
||||
"height": 768,
|
||||
},
|
||||
# Outpaint should not need a mask.
|
||||
unit_overrides={
|
||||
"image": girl_img,
|
||||
"model": get_model("v11p_sd15_inpaint"),
|
||||
"module": "inpaint_only+lama",
|
||||
"resize_mode": "Resize and Fill", # OUTER_FIT
|
||||
},
|
||||
).exec()
|
||||
347
extensions-builtin/sd_forge_controlnet/tests/web_api/template.py
Normal file
@@ -0,0 +1,347 @@
|
||||
import io
|
||||
import os
|
||||
import cv2
|
||||
import base64
|
||||
import functools
|
||||
from typing import Dict, Any, List, Union, Literal, Optional
|
||||
from pathlib import Path
|
||||
import datetime
|
||||
from enum import Enum
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
import requests
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def disable_in_cq(func):
|
||||
"""Skips the decorated test func in CQ run."""
|
||||
@functools.wraps(func)
|
||||
def wrapped_func(*args, **kwargs):
|
||||
if APITestTemplate.is_cq_run:
|
||||
pytest.skip()
|
||||
return func(*args, **kwargs)
|
||||
return wrapped_func
|
||||
|
||||
|
||||
PayloadOverrideType = Dict[str, Any]
|
||||
|
||||
timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
|
||||
test_result_dir = Path(__file__).parent / "results" / f"test_result_{timestamp}"
|
||||
test_expectation_dir = Path(__file__).parent / "expectations"
|
||||
os.makedirs(test_expectation_dir, exist_ok=True)
|
||||
resource_dir = Path(__file__).parents[1] / "images"
|
||||
|
||||
|
||||
def get_dest_dir():
|
||||
if APITestTemplate.is_set_expectation_run:
|
||||
return test_expectation_dir
|
||||
else:
|
||||
return test_result_dir
|
||||
|
||||
|
||||
def save_base64(base64img: str, dest: Path):
|
||||
Image.open(io.BytesIO(base64.b64decode(base64img.split(",", 1)[0]))).save(dest)
|
||||
|
||||
|
||||
def read_image(img_path: Path) -> str:
|
||||
img = cv2.imread(str(img_path))
|
||||
_, bytes = cv2.imencode(".png", img)
|
||||
encoded_image = base64.b64encode(bytes).decode("utf-8")
|
||||
return encoded_image
|
||||
|
||||
|
||||
def read_image_dir(img_dir: Path, suffixes=('.png', '.jpg', '.jpeg', '.webp')) -> List[str]:
|
||||
"""Try read all images in given img_dir."""
|
||||
img_dir = str(img_dir)
|
||||
images = []
|
||||
for filename in os.listdir(img_dir):
|
||||
if filename.endswith(suffixes):
|
||||
img_path = os.path.join(img_dir, filename)
|
||||
try:
|
||||
images.append(read_image(img_path))
|
||||
except IOError:
|
||||
print(f"Error opening {img_path}")
|
||||
return images
|
||||
|
||||
|
||||
girl_img = read_image(resource_dir / "1girl.png")
|
||||
mask_img = read_image(resource_dir / "mask.png")
|
||||
mask_small_img = read_image(resource_dir / "mask_small.png")
|
||||
portrait_imgs = read_image_dir(resource_dir / "portrait")
|
||||
realistic_girl_face_img = portrait_imgs[0]
|
||||
|
||||
|
||||
general_negative_prompt = """
|
||||
(worst quality:2), (low quality:2), (normal quality:2), lowres, normal quality,
|
||||
((monochrome)), ((grayscale)), skin spots, acnes, skin blemishes, age spot,
|
||||
backlight,(ugly:1.331), (duplicate:1.331), (morbid:1.21), (mutilated:1.21),
|
||||
(tranny:1.331), mutated hands, (poorly drawn hands:1.331), blurry, (bad anatomy:1.21),
|
||||
(bad proportions:1.331), extra limbs, (missing arms:1.331), (extra legs:1.331),
|
||||
(fused fingers:1.61051), (too many fingers:1.61051), (unclear eyes:1.331), bad hands,
|
||||
missing fingers, extra digit, bad body, easynegative, nsfw"""
|
||||
|
||||
class StableDiffusionVersion(Enum):
|
||||
"""The version family of stable diffusion model."""
|
||||
|
||||
UNKNOWN = 0
|
||||
SD1x = 1
|
||||
SD2x = 2
|
||||
SDXL = 3
|
||||
|
||||
|
||||
sd_version = StableDiffusionVersion(
|
||||
int(os.environ.get("CONTROLNET_TEST_SD_VERSION", StableDiffusionVersion.SD1x.value))
|
||||
)
|
||||
|
||||
is_full_coverage = os.environ.get("CONTROLNET_TEST_FULL_COVERAGE", None) is not None
|
||||
|
||||
|
||||
class APITestTemplate:
|
||||
is_set_expectation_run = os.environ.get("CONTROLNET_SET_EXP", "True") == "True"
|
||||
is_cq_run = os.environ.get("FORGE_CQ_TEST", "False") == "True"
|
||||
BASE_URL = "http://localhost:7860/"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
name: str,
|
||||
gen_type: Union[Literal["img2img"], Literal["txt2img"]],
|
||||
payload_overrides: PayloadOverrideType,
|
||||
unit_overrides: Union[PayloadOverrideType, List[PayloadOverrideType]],
|
||||
input_image: Optional[str] = None,
|
||||
):
|
||||
self.name = name
|
||||
self.url = APITestTemplate.BASE_URL + "sdapi/v1/" + gen_type
|
||||
self.payload = {
|
||||
**(txt2img_payload if gen_type == "txt2img" else img2img_payload),
|
||||
**payload_overrides,
|
||||
}
|
||||
if gen_type == "img2img" and input_image is not None:
|
||||
self.payload["init_images"] = [input_image]
|
||||
|
||||
# CQ runs on CPU. Reduce steps to increase test speed.
|
||||
if "steps" not in payload_overrides and APITestTemplate.is_cq_run:
|
||||
self.payload["steps"] = 3
|
||||
|
||||
unit_overrides = (
|
||||
unit_overrides
|
||||
if isinstance(unit_overrides, (list, tuple))
|
||||
else [unit_overrides]
|
||||
)
|
||||
self.payload["alwayson_scripts"]["ControlNet"]["args"] = [
|
||||
{
|
||||
**default_unit,
|
||||
**unit_override,
|
||||
**({"image": input_image} if gen_type == "txt2img" and input_image is not None else {}),
|
||||
}
|
||||
for unit_override in unit_overrides
|
||||
]
|
||||
self.active_unit_count = len(unit_overrides)
|
||||
|
||||
def exec(self, *args, **kwargs) -> bool:
|
||||
if APITestTemplate.is_cq_run:
|
||||
return self.exec_cq(*args, **kwargs)
|
||||
else:
|
||||
return self.exec_local(*args, **kwargs)
|
||||
|
||||
def exec_cq(self, expected_output_num: Optional[int] = None, *args, **kwargs) -> bool:
|
||||
"""Execute test in CQ environment."""
|
||||
res = requests.post(url=self.url, json=self.payload)
|
||||
if res.status_code != 200:
|
||||
print(f"Unexpected status code {res.status_code}")
|
||||
return False
|
||||
|
||||
response = res.json()
|
||||
if "images" not in response:
|
||||
print(response.keys())
|
||||
return False
|
||||
|
||||
if expected_output_num is None:
|
||||
expected_output_num = self.payload["n_iter"] * self.payload["batch_size"] + self.active_unit_count
|
||||
|
||||
if len(response["images"]) != expected_output_num:
|
||||
print(f"{len(response['images'])} != {expected_output_num}")
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
def exec_local(self, result_only: bool = True, *args, **kwargs) -> bool:
|
||||
"""Execute test in local environment."""
|
||||
if not APITestTemplate.is_set_expectation_run:
|
||||
os.makedirs(test_result_dir, exist_ok=True)
|
||||
|
||||
failed = False
|
||||
|
||||
response = requests.post(url=self.url, json=self.payload).json()
|
||||
if "images" not in response:
|
||||
print(response.keys())
|
||||
return False
|
||||
|
||||
dest_dir = get_dest_dir()
|
||||
results = response["images"][:1] if result_only else response["images"]
|
||||
for i, base64image in enumerate(results):
|
||||
img_file_name = f"{self.name}_{i}.png"
|
||||
save_base64(base64image, dest_dir / img_file_name)
|
||||
|
||||
if not APITestTemplate.is_set_expectation_run:
|
||||
try:
|
||||
img1 = cv2.imread(os.path.join(test_expectation_dir, img_file_name))
|
||||
img2 = cv2.imread(os.path.join(test_result_dir, img_file_name))
|
||||
except Exception as e:
|
||||
print(f"Get exception reading imgs: {e}")
|
||||
failed = True
|
||||
continue
|
||||
|
||||
if img1 is None:
|
||||
print(f"Warn: No expectation file found {img_file_name}.")
|
||||
continue
|
||||
|
||||
if not expect_same_image(
|
||||
img1,
|
||||
img2,
|
||||
diff_img_path=str(test_result_dir
|
||||
/ img_file_name.replace(".png", "_diff.png")),
|
||||
):
|
||||
failed = True
|
||||
return not failed
|
||||
|
||||
|
||||
def expect_same_image(img1, img2, diff_img_path: str) -> bool:
|
||||
# Calculate the difference between the two images
|
||||
diff = cv2.absdiff(img1, img2)
|
||||
|
||||
# Set a threshold to highlight the different pixels
|
||||
threshold = 30
|
||||
diff_highlighted = np.where(diff > threshold, 255, 0).astype(np.uint8)
|
||||
|
||||
# Assert that the two images are similar within a tolerance
|
||||
similar = np.allclose(img1, img2, rtol=0.5, atol=1)
|
||||
if not similar:
|
||||
# Save the diff_highlighted image to inspect the differences
|
||||
cv2.imwrite(diff_img_path, diff_highlighted)
|
||||
|
||||
matching_pixels = np.isclose(img1, img2, rtol=0.5, atol=1)
|
||||
similar_in_general = (matching_pixels.sum() / matching_pixels.size) >= 0.95
|
||||
return similar_in_general
|
||||
|
||||
|
||||
def get_model(model_name: str) -> str:
|
||||
""" Find an available model with specified model name."""
|
||||
if model_name.lower() == "none":
|
||||
return "None"
|
||||
|
||||
r = requests.get(APITestTemplate.BASE_URL + "controlnet/model_list")
|
||||
result = r.json()
|
||||
if "model_list" not in result:
|
||||
raise ValueError("No model available")
|
||||
|
||||
candidates = [
|
||||
model
|
||||
for model in result["model_list"]
|
||||
if model_name.lower() in model.lower()
|
||||
]
|
||||
|
||||
if not candidates:
|
||||
raise ValueError("No suitable model available")
|
||||
|
||||
return candidates[0]
|
||||
|
||||
|
||||
default_unit = {
|
||||
"control_mode": 0,
|
||||
"enabled": True,
|
||||
"guidance_end": 1,
|
||||
"guidance_start": 0,
|
||||
"pixel_perfect": True,
|
||||
"processor_res": 512,
|
||||
"resize_mode": 1,
|
||||
"threshold_a": 64,
|
||||
"threshold_b": 64,
|
||||
"weight": 1,
|
||||
"module": "canny",
|
||||
"model": get_model("sd15_canny"),
|
||||
}
|
||||
|
||||
img2img_payload = {
|
||||
"batch_size": 1,
|
||||
"cfg_scale": 7,
|
||||
"height": 768,
|
||||
"width": 512,
|
||||
"n_iter": 1,
|
||||
"steps": 10,
|
||||
"sampler_name": "Euler a",
|
||||
"prompt": "(masterpiece: 1.3), (highres: 1.3), best quality,",
|
||||
"negative_prompt": "",
|
||||
"seed": 42,
|
||||
"seed_enable_extras": False,
|
||||
"seed_resize_from_h": 0,
|
||||
"seed_resize_from_w": 0,
|
||||
"subseed": -1,
|
||||
"subseed_strength": 0,
|
||||
"override_settings": {},
|
||||
"override_settings_restore_afterwards": False,
|
||||
"do_not_save_grid": False,
|
||||
"do_not_save_samples": False,
|
||||
"s_churn": 0,
|
||||
"s_min_uncond": 0,
|
||||
"s_noise": 1,
|
||||
"s_tmax": None,
|
||||
"s_tmin": 0,
|
||||
"script_args": [],
|
||||
"script_name": None,
|
||||
"styles": [],
|
||||
"alwayson_scripts": {"ControlNet": {"args": [default_unit]}},
|
||||
"denoising_strength": 0.75,
|
||||
"initial_noise_multiplier": 1,
|
||||
"inpaint_full_res": 0,
|
||||
"inpaint_full_res_padding": 32,
|
||||
"inpainting_fill": 1,
|
||||
"inpainting_mask_invert": 0,
|
||||
"mask_blur_x": 4,
|
||||
"mask_blur_y": 4,
|
||||
"mask_blur": 4,
|
||||
"resize_mode": 0,
|
||||
}
|
||||
|
||||
txt2img_payload = {
|
||||
"alwayson_scripts": {"ControlNet": {"args": [default_unit]}},
|
||||
"batch_size": 1,
|
||||
"cfg_scale": 7,
|
||||
"comments": {},
|
||||
"disable_extra_networks": False,
|
||||
"do_not_save_grid": False,
|
||||
"do_not_save_samples": False,
|
||||
"enable_hr": False,
|
||||
"height": 768,
|
||||
"hr_negative_prompt": "",
|
||||
"hr_prompt": "",
|
||||
"hr_resize_x": 0,
|
||||
"hr_resize_y": 0,
|
||||
"hr_scale": 2,
|
||||
"hr_second_pass_steps": 0,
|
||||
"hr_upscaler": "Latent",
|
||||
"n_iter": 1,
|
||||
"negative_prompt": "",
|
||||
"override_settings": {},
|
||||
"override_settings_restore_afterwards": True,
|
||||
"prompt": "(masterpiece: 1.3), (highres: 1.3), best quality,",
|
||||
"restore_faces": False,
|
||||
"s_churn": 0.0,
|
||||
"s_min_uncond": 0,
|
||||
"s_noise": 1.0,
|
||||
"s_tmax": None,
|
||||
"s_tmin": 0.0,
|
||||
"sampler_name": "Euler a",
|
||||
"script_args": [],
|
||||
"script_name": None,
|
||||
"seed": 42,
|
||||
"seed_enable_extras": True,
|
||||
"seed_resize_from_h": -1,
|
||||
"seed_resize_from_w": -1,
|
||||
"steps": 10,
|
||||
"styles": [],
|
||||
"subseed": -1,
|
||||
"subseed_strength": 0,
|
||||
"tiling": False,
|
||||
"width": 512,
|
||||
}
|
||||
21
extensions-builtin/sd_forge_dynamic_thresholding/LICENSE.txt
Normal file
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2023 Alex "mcmonkey" Goodwin
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,49 @@
|
||||
# https://github.com/mcmonkeyprojects/sd-dynamic-thresholding
|
||||
|
||||
|
||||
from lib_dynamic_thresholding.dynthres_core import DynThresh
|
||||
|
||||
|
||||
class DynamicThresholdingNode:
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"model": ("MODEL",),
|
||||
"mimic_scale": ("FLOAT", {"default": 7.0, "min": 0.0, "max": 100.0, "step": 0.5}),
|
||||
"threshold_percentile": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
|
||||
"mimic_mode": (DynThresh.Modes, ),
|
||||
"mimic_scale_min": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 100.0, "step": 0.5}),
|
||||
"cfg_mode": (DynThresh.Modes, ),
|
||||
"cfg_scale_min": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 100.0, "step": 0.5}),
|
||||
"sched_val": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 100.0, "step": 0.01}),
|
||||
"separate_feature_channels": (["enable", "disable"], ),
|
||||
"scaling_startpoint": (DynThresh.Startpoints, ),
|
||||
"variability_measure": (DynThresh.Variabilities, ),
|
||||
"interpolate_phi": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("MODEL",)
|
||||
FUNCTION = "patch"
|
||||
CATEGORY = "advanced/mcmonkey"
|
||||
|
||||
def patch(self, model, mimic_scale, threshold_percentile, mimic_mode, mimic_scale_min, cfg_mode, cfg_scale_min, sched_val, separate_feature_channels, scaling_startpoint, variability_measure, interpolate_phi):
|
||||
|
||||
dynamic_thresh = DynThresh(mimic_scale, threshold_percentile, mimic_mode, mimic_scale_min, cfg_mode, cfg_scale_min, sched_val, 0, 999, separate_feature_channels == "enable", scaling_startpoint, variability_measure, interpolate_phi)
|
||||
|
||||
def sampler_dyn_thresh(args):
|
||||
input = args["input"]
|
||||
cond = input - args["cond"]
|
||||
uncond = input - args["uncond"]
|
||||
cond_scale = args["cond_scale"]
|
||||
time_step = model.model.model_sampling.timestep(args["sigma"])
|
||||
time_step = time_step[0].item()
|
||||
dynamic_thresh.step = 999 - time_step
|
||||
|
||||
return input - dynamic_thresh.dynthresh(cond, uncond, cond_scale, None)
|
||||
|
||||
m = model.clone()
|
||||
m.set_model_sampler_cfg_function(sampler_dyn_thresh)
|
||||
return (m, )
|
||||
@@ -0,0 +1,170 @@
|
||||
# https://github.com/mcmonkeyprojects/sd-dynamic-thresholding
|
||||
|
||||
|
||||
import torch, math
|
||||
|
||||
######################### DynThresh Core #########################
|
||||
|
||||
class DynThresh:
|
||||
|
||||
Modes = ["Constant", "Linear Down", "Cosine Down", "Half Cosine Down", "Linear Up", "Cosine Up", "Half Cosine Up", "Power Up", "Power Down", "Linear Repeating", "Cosine Repeating", "Sawtooth"]
|
||||
Startpoints = ["MEAN", "ZERO"]
|
||||
Variabilities = ["AD", "STD"]
|
||||
|
||||
def __init__(self, mimic_scale, threshold_percentile, mimic_mode, mimic_scale_min, cfg_mode, cfg_scale_min, sched_val, experiment_mode, max_steps, separate_feature_channels, scaling_startpoint, variability_measure, interpolate_phi):
|
||||
self.mimic_scale = mimic_scale
|
||||
self.threshold_percentile = threshold_percentile
|
||||
self.mimic_mode = mimic_mode
|
||||
self.cfg_mode = cfg_mode
|
||||
self.max_steps = max_steps
|
||||
self.cfg_scale_min = cfg_scale_min
|
||||
self.mimic_scale_min = mimic_scale_min
|
||||
self.experiment_mode = experiment_mode
|
||||
self.sched_val = sched_val
|
||||
self.sep_feat_channels = separate_feature_channels
|
||||
self.scaling_startpoint = scaling_startpoint
|
||||
self.variability_measure = variability_measure
|
||||
self.interpolate_phi = interpolate_phi
|
||||
|
||||
def interpret_scale(self, scale, mode, min):
|
||||
scale -= min
|
||||
max = self.max_steps - 1
|
||||
frac = self.step / max
|
||||
if mode == "Constant":
|
||||
pass
|
||||
elif mode == "Linear Down":
|
||||
scale *= 1.0 - frac
|
||||
elif mode == "Half Cosine Down":
|
||||
scale *= math.cos(frac)
|
||||
elif mode == "Cosine Down":
|
||||
scale *= math.cos(frac * 1.5707)
|
||||
elif mode == "Linear Up":
|
||||
scale *= frac
|
||||
elif mode == "Half Cosine Up":
|
||||
scale *= 1.0 - math.cos(frac)
|
||||
elif mode == "Cosine Up":
|
||||
scale *= 1.0 - math.cos(frac * 1.5707)
|
||||
elif mode == "Power Up":
|
||||
scale *= math.pow(frac, self.sched_val)
|
||||
elif mode == "Power Down":
|
||||
scale *= 1.0 - math.pow(frac, self.sched_val)
|
||||
elif mode == "Linear Repeating":
|
||||
portion = (frac * self.sched_val) % 1.0
|
||||
scale *= (0.5 - portion) * 2 if portion < 0.5 else (portion - 0.5) * 2
|
||||
elif mode == "Cosine Repeating":
|
||||
scale *= math.cos(frac * 6.28318 * self.sched_val) * 0.5 + 0.5
|
||||
elif mode == "Sawtooth":
|
||||
scale *= (frac * self.sched_val) % 1.0
|
||||
scale += min
|
||||
return scale
|
||||
|
||||
def dynthresh(self, cond, uncond, cfg_scale, weights):
|
||||
mimic_scale = self.interpret_scale(self.mimic_scale, self.mimic_mode, self.mimic_scale_min)
|
||||
cfg_scale = self.interpret_scale(cfg_scale, self.cfg_mode, self.cfg_scale_min)
|
||||
# uncond shape is (batch, 4, height, width)
|
||||
conds_per_batch = cond.shape[0] / uncond.shape[0]
|
||||
assert conds_per_batch == int(conds_per_batch), "Expected # of conds per batch to be constant across batches"
|
||||
cond_stacked = cond.reshape((-1, int(conds_per_batch)) + uncond.shape[1:])
|
||||
|
||||
### Normal first part of the CFG Scale logic, basically
|
||||
diff = cond_stacked - uncond.unsqueeze(1)
|
||||
if weights is not None:
|
||||
diff = diff * weights
|
||||
relative = diff.sum(1)
|
||||
|
||||
### Get the normal result for both mimic and normal scale
|
||||
mim_target = uncond + relative * mimic_scale
|
||||
cfg_target = uncond + relative * cfg_scale
|
||||
### If we weren't doing mimic scale, we'd just return cfg_target here
|
||||
|
||||
### Now recenter the values relative to their average rather than absolute, to allow scaling from average
|
||||
mim_flattened = mim_target.flatten(2)
|
||||
cfg_flattened = cfg_target.flatten(2)
|
||||
mim_means = mim_flattened.mean(dim=2).unsqueeze(2)
|
||||
cfg_means = cfg_flattened.mean(dim=2).unsqueeze(2)
|
||||
mim_centered = mim_flattened - mim_means
|
||||
cfg_centered = cfg_flattened - cfg_means
|
||||
|
||||
if self.sep_feat_channels:
|
||||
if self.variability_measure == 'STD':
|
||||
mim_scaleref = mim_centered.std(dim=2).unsqueeze(2)
|
||||
cfg_scaleref = cfg_centered.std(dim=2).unsqueeze(2)
|
||||
else: # 'AD'
|
||||
mim_scaleref = mim_centered.abs().max(dim=2).values.unsqueeze(2)
|
||||
cfg_scaleref = torch.quantile(cfg_centered.abs(), self.threshold_percentile, dim=2).unsqueeze(2)
|
||||
|
||||
else:
|
||||
if self.variability_measure == 'STD':
|
||||
mim_scaleref = mim_centered.std()
|
||||
cfg_scaleref = cfg_centered.std()
|
||||
else: # 'AD'
|
||||
mim_scaleref = mim_centered.abs().max()
|
||||
cfg_scaleref = torch.quantile(cfg_centered.abs(), self.threshold_percentile)
|
||||
|
||||
if self.scaling_startpoint == 'ZERO':
|
||||
scaling_factor = mim_scaleref / cfg_scaleref
|
||||
result = cfg_flattened * scaling_factor
|
||||
|
||||
else: # 'MEAN'
|
||||
if self.variability_measure == 'STD':
|
||||
cfg_renormalized = (cfg_centered / cfg_scaleref) * mim_scaleref
|
||||
else: # 'AD'
|
||||
### Get the maximum value of all datapoints (with an optional threshold percentile on the uncond)
|
||||
max_scaleref = torch.maximum(mim_scaleref, cfg_scaleref)
|
||||
### Clamp to the max
|
||||
cfg_clamped = cfg_centered.clamp(-max_scaleref, max_scaleref)
|
||||
### Now shrink from the max to normalize and grow to the mimic scale (instead of the CFG scale)
|
||||
cfg_renormalized = (cfg_clamped / max_scaleref) * mim_scaleref
|
||||
|
||||
### Now add it back onto the averages to get into real scale again and return
|
||||
result = cfg_renormalized + cfg_means
|
||||
|
||||
actual_res = result.unflatten(2, mim_target.shape[2:])
|
||||
|
||||
if self.interpolate_phi != 1.0:
|
||||
actual_res = actual_res * self.interpolate_phi + cfg_target * (1.0 - self.interpolate_phi)
|
||||
|
||||
if self.experiment_mode == 1:
|
||||
num = actual_res.cpu().numpy()
|
||||
for y in range(0, 64):
|
||||
for x in range (0, 64):
|
||||
if num[0][0][y][x] > 1.0:
|
||||
num[0][1][y][x] *= 0.5
|
||||
if num[0][1][y][x] > 1.0:
|
||||
num[0][1][y][x] *= 0.5
|
||||
if num[0][2][y][x] > 1.5:
|
||||
num[0][2][y][x] *= 0.5
|
||||
actual_res = torch.from_numpy(num).to(device=uncond.device)
|
||||
elif self.experiment_mode == 2:
|
||||
num = actual_res.cpu().numpy()
|
||||
for y in range(0, 64):
|
||||
for x in range (0, 64):
|
||||
over_scale = False
|
||||
for z in range(0, 4):
|
||||
if abs(num[0][z][y][x]) > 1.5:
|
||||
over_scale = True
|
||||
if over_scale:
|
||||
for z in range(0, 4):
|
||||
num[0][z][y][x] *= 0.7
|
||||
actual_res = torch.from_numpy(num).to(device=uncond.device)
|
||||
elif self.experiment_mode == 3:
|
||||
coefs = torch.tensor([
|
||||
# R G B W
|
||||
[0.298, 0.207, 0.208, 0.0], # L1
|
||||
[0.187, 0.286, 0.173, 0.0], # L2
|
||||
[-0.158, 0.189, 0.264, 0.0], # L3
|
||||
[-0.184, -0.271, -0.473, 1.0], # L4
|
||||
], device=uncond.device)
|
||||
res_rgb = torch.einsum("laxy,ab -> lbxy", actual_res, coefs)
|
||||
max_r, max_g, max_b, max_w = res_rgb[0][0].max(), res_rgb[0][1].max(), res_rgb[0][2].max(), res_rgb[0][3].max()
|
||||
max_rgb = max(max_r, max_g, max_b)
|
||||
print(f"test max = r={max_r}, g={max_g}, b={max_b}, w={max_w}, rgb={max_rgb}")
|
||||
if self.step / (self.max_steps - 1) > 0.2:
|
||||
if max_rgb < 2.0 and max_w < 3.0:
|
||||
res_rgb /= max_rgb / 2.4
|
||||
else:
|
||||
if max_rgb > 2.4 and max_w > 3.0:
|
||||
res_rgb /= max_rgb / 2.4
|
||||
actual_res = torch.einsum("laxy,ab -> lbxy", res_rgb, coefs.inverse())
|
||||
|
||||
return actual_res
|
||||
@@ -0,0 +1,81 @@
|
||||
import gradio as gr
|
||||
|
||||
from modules import scripts
|
||||
from lib_dynamic_thresholding.dynthres import DynamicThresholdingNode
|
||||
|
||||
opDynamicThresholdingNode = DynamicThresholdingNode().patch
|
||||
|
||||
|
||||
class DynamicThresholdingForForge(scripts.Script):
|
||||
sorting_priority = 11
|
||||
|
||||
def title(self):
|
||||
return "DynamicThresholding (CFG-Fix) Integrated"
|
||||
|
||||
def show(self, is_img2img):
|
||||
# make this extension visible in both txt2img and img2img tab.
|
||||
return scripts.AlwaysVisible
|
||||
|
||||
def ui(self, *args, **kwargs):
|
||||
with gr.Accordion(open=False, label=self.title()):
|
||||
enabled = gr.Checkbox(label='Enabled', value=False)
|
||||
mimic_scale = gr.Slider(label='Mimic Scale', minimum=0.0, maximum=100.0, step=0.5, value=7.0)
|
||||
threshold_percentile = gr.Slider(label='Threshold Percentile', minimum=0.0, maximum=1.0, step=0.01,
|
||||
value=1.0)
|
||||
mimic_mode = gr.Radio(label='Mimic Mode',
|
||||
choices=['Constant', 'Linear Down', 'Cosine Down', 'Half Cosine Down', 'Linear Up',
|
||||
'Cosine Up', 'Half Cosine Up', 'Power Up', 'Power Down', 'Linear Repeating',
|
||||
'Cosine Repeating', 'Sawtooth'], value='Constant')
|
||||
mimic_scale_min = gr.Slider(label='Mimic Scale Min', minimum=0.0, maximum=100.0, step=0.5, value=0.0)
|
||||
cfg_mode = gr.Radio(label='Cfg Mode',
|
||||
choices=['Constant', 'Linear Down', 'Cosine Down', 'Half Cosine Down', 'Linear Up',
|
||||
'Cosine Up', 'Half Cosine Up', 'Power Up', 'Power Down', 'Linear Repeating',
|
||||
'Cosine Repeating', 'Sawtooth'], value='Constant')
|
||||
cfg_scale_min = gr.Slider(label='Cfg Scale Min', minimum=0.0, maximum=100.0, step=0.5, value=0.0)
|
||||
sched_val = gr.Slider(label='Sched Val', minimum=0.0, maximum=100.0, step=0.01, value=1.0)
|
||||
separate_feature_channels = gr.Radio(label='Separate Feature Channels', choices=['enable', 'disable'],
|
||||
value='enable')
|
||||
scaling_startpoint = gr.Radio(label='Scaling Startpoint', choices=['MEAN', 'ZERO'], value='MEAN')
|
||||
variability_measure = gr.Radio(label='Variability Measure', choices=['AD', 'STD'], value='AD')
|
||||
interpolate_phi = gr.Slider(label='Interpolate Phi', minimum=0.0, maximum=1.0, step=0.01, value=1.0)
|
||||
|
||||
return enabled, mimic_scale, threshold_percentile, mimic_mode, mimic_scale_min, cfg_mode, cfg_scale_min, \
|
||||
sched_val, separate_feature_channels, scaling_startpoint, variability_measure, interpolate_phi
|
||||
|
||||
def process_before_every_sampling(self, p, *script_args, **kwargs):
|
||||
# This will be called before every sampling.
|
||||
# If you use highres fix, this will be called twice.
|
||||
|
||||
enabled, mimic_scale, threshold_percentile, mimic_mode, mimic_scale_min, cfg_mode, cfg_scale_min, \
|
||||
sched_val, separate_feature_channels, scaling_startpoint, variability_measure, \
|
||||
interpolate_phi = script_args
|
||||
|
||||
if not enabled:
|
||||
return
|
||||
|
||||
unet = p.sd_model.forge_objects.unet
|
||||
|
||||
unet = opDynamicThresholdingNode(unet, mimic_scale, threshold_percentile, mimic_mode, mimic_scale_min,
|
||||
cfg_mode, cfg_scale_min, sched_val, separate_feature_channels,
|
||||
scaling_startpoint, variability_measure, interpolate_phi)[0]
|
||||
|
||||
p.sd_model.forge_objects.unet = unet
|
||||
|
||||
# Below codes will add some logs to the texts below the image outputs on UI.
|
||||
# The extra_generation_params does not influence results.
|
||||
p.extra_generation_params.update(dict(
|
||||
dynthres_enabled=enabled,
|
||||
dynthres_mimic_scale=mimic_scale,
|
||||
dynthres_threshold_percentile=threshold_percentile,
|
||||
dynthres_mimic_mode=mimic_mode,
|
||||
dynthres_mimic_scale_min=mimic_scale_min,
|
||||
dynthres_cfg_mode=cfg_mode,
|
||||
dynthres_cfg_scale_min=cfg_scale_min,
|
||||
dynthres_sched_val=sched_val,
|
||||
dynthres_separate_feature_channels=separate_feature_channels,
|
||||
dynthres_scaling_startpoint=scaling_startpoint,
|
||||
dynthres_variability_measure=variability_measure,
|
||||
dynthres_interpolate_phi=interpolate_phi,
|
||||
))
|
||||
|
||||
return
|
||||
@@ -0,0 +1,131 @@
|
||||
import os
|
||||
import torch
|
||||
import copy
|
||||
|
||||
from modules_forge.shared import add_supported_control_model
|
||||
from modules_forge.supported_controlnet import ControlModelPatcher
|
||||
from modules_forge.forge_sampler import sampling_prepare
|
||||
from ldm_patched.modules.utils import load_torch_file
|
||||
from ldm_patched.modules import model_patcher
|
||||
from ldm_patched.modules.model_management import cast_to_device, current_loaded_models
|
||||
from ldm_patched.modules.lora import model_lora_keys_unet
|
||||
|
||||
|
||||
def is_model_loaded(model):
|
||||
return any(model == m.model for m in current_loaded_models)
|
||||
|
||||
|
||||
class InpaintHead(torch.nn.Module):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.head = torch.nn.Parameter(torch.empty(size=(320, 5, 3, 3), device="cpu"))
|
||||
|
||||
def __call__(self, x):
|
||||
x = torch.nn.functional.pad(x, (1, 1, 1, 1), "replicate")
|
||||
return torch.nn.functional.conv2d(input=x, weight=self.head)
|
||||
|
||||
|
||||
def load_fooocus_patch(lora: dict, to_load: dict):
|
||||
patch_dict = {}
|
||||
loaded_keys = set()
|
||||
for key in to_load.values():
|
||||
if value := lora.get(key, None):
|
||||
patch_dict[key] = ("fooocus", value)
|
||||
loaded_keys.add(key)
|
||||
|
||||
not_loaded = sum(1 for x in lora if x not in loaded_keys)
|
||||
print(f"[Fooocus Patch Loader] {len(loaded_keys)} keys loaded, {not_loaded} remaining keys not found in model.")
|
||||
return patch_dict
|
||||
|
||||
|
||||
def calculate_weight_fooocus(weight, alpha, v):
|
||||
w1 = cast_to_device(v[0], weight.device, torch.float32)
|
||||
if w1.shape == weight.shape:
|
||||
w_min = cast_to_device(v[1], weight.device, torch.float32)
|
||||
w_max = cast_to_device(v[2], weight.device, torch.float32)
|
||||
w1 = (w1 / 255.0) * (w_max - w_min) + w_min
|
||||
weight += alpha * cast_to_device(w1, weight.device, weight.dtype)
|
||||
else:
|
||||
print(f"[Fooocus Patch Loader] weight not merged ({w1.shape} != {weight.shape})")
|
||||
return weight
|
||||
|
||||
|
||||
class FooocusInpaintPatcher(ControlModelPatcher):
|
||||
@staticmethod
|
||||
def try_build_from_state_dict(state_dict, ckpt_path):
|
||||
if 'diffusion_model.time_embed.0.weight' in state_dict:
|
||||
if len(state_dict['diffusion_model.time_embed.0.weight']) == 3:
|
||||
return FooocusInpaintPatcher(state_dict)
|
||||
|
||||
return None
|
||||
|
||||
def __init__(self, state_dict):
|
||||
super().__init__()
|
||||
self.state_dict = state_dict
|
||||
self.inpaint_head = InpaintHead().to(device=torch.device('cpu'), dtype=torch.float32)
|
||||
self.inpaint_head.load_state_dict(load_torch_file(os.path.join(os.path.dirname(__file__), 'fooocus_inpaint_head')))
|
||||
|
||||
return
|
||||
|
||||
def process_before_every_sampling(self, process, cond, mask, *args, **kwargs):
|
||||
cond_original = kwargs['cond_original']
|
||||
mask_original = kwargs['mask_original']
|
||||
|
||||
unet_original = process.sd_model.forge_objects.unet.clone()
|
||||
unet = process.sd_model.forge_objects.unet.clone()
|
||||
vae = process.sd_model.forge_objects.vae
|
||||
|
||||
latent_image = vae.encode(cond_original.movedim(1, -1))
|
||||
latent_image = process.sd_model.forge_objects.unet.model.latent_format.process_in(latent_image)
|
||||
latent_mask = torch.nn.functional.max_pool2d(mask_original, (8, 8)).round().to(cond)
|
||||
feed = torch.cat([
|
||||
latent_mask.to(device=torch.device('cpu'), dtype=torch.float32),
|
||||
latent_image.to(device=torch.device('cpu'), dtype=torch.float32)
|
||||
], dim=1)
|
||||
inpaint_head_feature = self.inpaint_head(feed)
|
||||
|
||||
def input_block_patch(h, transformer_options):
|
||||
if transformer_options["block"][1] == 0:
|
||||
h = h + inpaint_head_feature.to(h)
|
||||
return h
|
||||
|
||||
unet.set_model_input_block_patch(input_block_patch)
|
||||
|
||||
lora_keys = model_lora_keys_unet(unet.model, {})
|
||||
lora_keys.update({x: x for x in unet.model.state_dict().keys()})
|
||||
loaded_lora = load_fooocus_patch(self.state_dict, lora_keys)
|
||||
|
||||
patched = unet.add_patches(loaded_lora, 1.0)
|
||||
|
||||
not_patched_count = sum(1 for x in loaded_lora if x not in patched)
|
||||
|
||||
if not_patched_count > 0:
|
||||
print(f"[Fooocus Patch Loader] Failed to load {not_patched_count} keys")
|
||||
|
||||
sigma_start = unet.model.model_sampling.percent_to_sigma(self.start_percent)
|
||||
sigma_end = unet.model.model_sampling.percent_to_sigma(self.end_percent)
|
||||
|
||||
def conditioning_modifier(model, x, timestep, uncond, cond, cond_scale, model_options, seed):
|
||||
if timestep > sigma_start or timestep < sigma_end:
|
||||
target_model = unet_original
|
||||
model_options = copy.deepcopy(model_options)
|
||||
if 'transformer_options' in model_options:
|
||||
if 'patches' in model_options['transformer_options']:
|
||||
if 'input_block_patch' in model_options['transformer_options']['patches']:
|
||||
del model_options['transformer_options']['patches']['input_block_patch']
|
||||
else:
|
||||
target_model = unet
|
||||
|
||||
if not is_model_loaded(target_model):
|
||||
sampling_prepare(target_model, x)
|
||||
|
||||
return target_model.model, x, timestep, uncond, cond, cond_scale, model_options, seed
|
||||
|
||||
unet.add_conditioning_modifier(conditioning_modifier)
|
||||
|
||||
process.sd_model.forge_objects.unet = unet
|
||||
return
|
||||
|
||||
|
||||
model_patcher.extra_weight_calculators['fooocus'] = calculate_weight_fooocus
|
||||
add_supported_control_model(FooocusInpaintPatcher)
|
||||
@@ -43,6 +43,8 @@ opFreeU_V2 = FreeU_V2()
|
||||
|
||||
|
||||
class FreeUForForge(scripts.Script):
|
||||
sorting_priority = 12
|
||||
|
||||
def title(self):
|
||||
return "FreeU Integrated"
|
||||
|
||||
|
||||
@@ -8,6 +8,8 @@ opHyperTile = HyperTile()
|
||||
|
||||
|
||||
class HyperTileForForge(scripts.Script):
|
||||
sorting_priority = 13
|
||||
|
||||
def title(self):
|
||||
return "HyperTile Integrated"
|
||||
|
||||
|
||||
@@ -188,9 +188,8 @@ def zeroed_hidden_states(clip_vision, batch_size):
|
||||
image = torch.zeros([batch_size, 224, 224, 3])
|
||||
ldm_patched.modules.model_management.load_model_gpu(clip_vision.patcher)
|
||||
pixel_values = clip_preprocess(image.to(clip_vision.load_device)).float()
|
||||
outputs = clip_vision.model(pixel_values=pixel_values, intermediate_output=-2)
|
||||
# we only need the penultimate hidden states
|
||||
outputs = outputs[1].to(ldm_patched.modules.model_management.intermediate_device())
|
||||
outputs = clip_vision.model(pixel_values=pixel_values, output_hidden_states=True)
|
||||
outputs = outputs.hidden_states[-2].to(ldm_patched.modules.model_management.intermediate_device())
|
||||
return outputs
|
||||
|
||||
def min_(tensor_list):
|
||||
@@ -343,18 +342,15 @@ class IPAdapter(nn.Module):
|
||||
)
|
||||
return image_proj_model
|
||||
|
||||
@torch.inference_mode()
|
||||
def get_image_embeds(self, clip_embed, clip_embed_zeroed):
|
||||
image_prompt_embeds = self.image_proj_model(clip_embed)
|
||||
uncond_image_prompt_embeds = self.image_proj_model(clip_embed_zeroed)
|
||||
return image_prompt_embeds, uncond_image_prompt_embeds
|
||||
|
||||
@torch.inference_mode()
|
||||
def get_image_embeds_faceid_plus(self, face_embed, clip_embed, s_scale, shortcut):
|
||||
embeds = self.image_proj_model(face_embed, clip_embed, scale=s_scale, shortcut=shortcut)
|
||||
return embeds
|
||||
|
||||
@torch.inference_mode()
|
||||
def get_image_embeds_instantid(self, prompt_image_emb):
|
||||
c = self.image_proj_model(prompt_image_emb)
|
||||
uc = self.image_proj_model(torch.zeros_like(prompt_image_emb))
|
||||
@@ -391,7 +387,9 @@ class CrossAttentionPatch:
|
||||
def __call__(self, n, context_attn2, value_attn2, extra_options):
|
||||
org_dtype = n.dtype
|
||||
cond_or_uncond = extra_options["cond_or_uncond"]
|
||||
sigma = extra_options["sigmas"][0].item() if 'sigmas' in extra_options else 999999999.9
|
||||
|
||||
sigma = extra_options["sigmas"][0] if 'sigmas' in extra_options else None
|
||||
sigma = sigma.item() if sigma is not None else 999999999.9
|
||||
|
||||
# extra options for AnimateDiff
|
||||
ad_params = extra_options['ad_params'] if "ad_params" in extra_options else None
|
||||
@@ -466,7 +464,7 @@ class CrossAttentionPatch:
|
||||
ip_k = ip_k * W
|
||||
ip_v = ip_v_offset + ip_v_mean * W
|
||||
|
||||
out_ip = optimized_attention(q, ip_k, ip_v, extra_options["n_heads"])
|
||||
out_ip = optimized_attention(q, ip_k.to(org_dtype), ip_v.to(org_dtype), extra_options["n_heads"])
|
||||
if weight_type.startswith("original"):
|
||||
out_ip = out_ip * weight
|
||||
|
||||
|
||||
@@ -8,6 +8,8 @@ opPatchModelAddDownscale = PatchModelAddDownscale()
|
||||
|
||||
|
||||
class KohyaHRFixForForge(scripts.Script):
|
||||
sorting_priority = 14
|
||||
|
||||
def title(self):
|
||||
return "Kohya HRFix Integrated"
|
||||
|
||||
|
||||
674
extensions-builtin/sd_forge_latent_modifier/LICENSE
Normal file
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
70
extensions-builtin/sd_forge_latent_modifier/README.md
Normal file
@@ -0,0 +1,70 @@
|
||||
This extension is compiled from https://github.com/Clybius
|
||||
Original Licence GPL V3
|
||||
|
||||
|
||||
## Latent Diffusion Mega Modifier (sampler_mega_modifier.py)
|
||||
### Adds multiple parameters to control the diffusion process towards a quality the user expects.
|
||||
* Sharpness: utilizes code from Fooocus's sampling process to sharpen the noise in the middle of the diffusion process.
|
||||
This can lead to more perceptual detail, especially at higher strengths.
|
||||
|
||||
* Tonemap: Clamps conditioning noise (CFG) using a user-chosen method, which can allow for the use of higher CFG values.
|
||||
|
||||
* Rescale: Scales the CFG by comparing the standard deviation to the existing latent to dynamically lower the CFG.
|
||||
|
||||
* Extra Noise: Adds extra noise in the middle of the diffusion process to conditioning, and do the inverse operation on unconditioning, if chosen.
|
||||
|
||||
* Contrast: Adjusts the contrast of the conditioning, can lead to more pop-style results. Essentially functions as a secondary CFG slider for stylization, without changing subject pose and location much, if at all.
|
||||
|
||||
* Combat CFG Drift: As we increase CFG, the mean will slightly drift away from 0. This subtracts the mean or median of the latent. Can lead to potentially sharper and higher frequency results, but may result in discoloration.
|
||||
|
||||
* Divisive Norm: Normalizes the latent using avg_pool2d, and can reduce noisy artifacts, due in part to features such as sharpness.
|
||||
|
||||
* Spectral Modulation: Converts the latent to frequencies, and clamps higher frequencies while boosting lower ones, then converts it back to an image latent. This effectively can be treated as a solution to oversaturation or burning as a result of higher CFG values, while not touching values around the median.
|
||||
|
||||
### Tonemapping Methods Explanation:
|
||||
* Reinhard: <p>Uses the reinhard method of tonemapping (from comfyanonymous' ComfyUI Experiments) to clamp the CFG if the difference is too strong.
|
||||
|
||||
Lower `tonemap_multiplier` clamps more noise, and a lower `tonemap_percentile` will increase the calculated standard deviation from the original noise. Play with it!</p>
|
||||
* Arctan: <p>Clamps the values dynamically using a simple arctan curve. [Link to interactive Desmos visualization](https://www.desmos.com/calculator/e4nrcdpqbl).
|
||||
|
||||
Recommended values for testing: tonemap_multiplier of 5, tonemap_percentile of 90.</p>
|
||||
* Quantile: <p>Clamps the values using torch.quantile for obtaining the highest magnitudes, and clamping based on the result.
|
||||
|
||||
|
||||
`Closer to 100 percentile == stronger clamping`. Recommended values for testing: tonemap_multiplier of 1, tonemap_percentile of 99.</p>
|
||||
* Gated: <p>Clamps the values using torch.quantile, only if above a specific floor value, which is set by `tonemapping_multiplier`. Clamps the noise prediction latent based on the percentile.
|
||||
|
||||
|
||||
`Closer to 100 percentile == stronger clamping, lower tonemapping_multiplier == stronger clamping`. Recommended values for testing: tonemap_multiplier of 0.8-1, tonemap_percentile of 99.995.</p>
|
||||
* CFG-Mimic: <p>Attempts to mimic a lower or higher CFG based on `tonemapping_multiplier`, and clamps it using `tonemapping_percentile` with torch.quantile.
|
||||
|
||||
|
||||
`Closer to 100 percentile == stronger clamping, lower tonemapping_multiplier == stronger clamping`. Recommended values for testing: tonemap_multiplier of 0.33-1.0, tonemap_percentile of 100.</p>
|
||||
* Spatial-Norm: <p>Clamps the values according to the noise prediction's absolute mean in the spectral domain. `tonemap_multiplier` adjusts the strength of the clamping.
|
||||
|
||||
|
||||
`Lower tonemapping_multiplier == stronger clamping`. Recommended value for testing: tonemap_multiplier of 0.5-2.0.</p>
|
||||
|
||||
### Contrast Explanation:
|
||||
<p>Scales the pixel values by the standard deviation, achieving a more contrasty look. In practice, this can effectively act as a secondary CFG slider for stylization. It doesn't modify subject poses much, if at all, which can be great for those looking to get more oomf out of their low-cfg setups.
|
||||
|
||||
Using a negative value will apply the inverse of the operation to the latent.</p>
|
||||
|
||||
### Spectral Modification Explanation:
|
||||
<p>We boost the low frequencies (low rate of change in the noise), and we lower the high frequencies (high rates of change in the noise).
|
||||
|
||||
Change the low/high frequency range using `spectral_mod_percentile` (default of 5.0, which is the upper and lower 5th percentiles.)
|
||||
|
||||
Increase/Decrease the strength of the adjustment by increasing `spectral_mod_multiplier`
|
||||
|
||||
Beware of percentile values higher than 15 and multiplier values higher than 5, especially for hard clamping. Here be dragons, as large values may cause it to "noise-out", or become full of non-sensical noise, especially earlier in the diffusion process.</p>
|
||||
|
||||
|
||||
#### Current Pipeline:
|
||||
>##### Add extra noise to conditioning -> Sharpen conditioning -> Convert to Noise Prediction -> Tonemap Noise Prediction -> Spectral Modification -> Modify contrast of noise prediction -> Rescale CFG -> Divisive Normalization -> Combat CFG Drift
|
||||
|
||||
#### Why use this over `x` node?
|
||||
Since the `set_model_sampler_cfg_function` hijack in ComfyUI can only utilize a single function, we bundle many latent modification methods into one large function for processing. This is simpler than taking an existing hijack and modifying it, which may be possible, but my (Clybius') lack of Python/PyTorch knowledge leads to this being the optimal method for simplicity. If you know how to do this, feel free to reach out through any means!
|
||||
|
||||
#### Can you implement `x` function?
|
||||
Depends. Is there existing code for such a function, with an open license for possible use in this repository? I could likely attempt adding it! Feel free to start an issue or to reach out for ideas you'd want implemented.
|
||||
@@ -0,0 +1,106 @@
|
||||
import gradio as gr
|
||||
from modules import scripts
|
||||
|
||||
from lib_latent_modifier.sampler_mega_modifier import ModelSamplerLatentMegaModifier
|
||||
|
||||
opModelSamplerLatentMegaModifier = ModelSamplerLatentMegaModifier().mega_modify
|
||||
|
||||
|
||||
class LatentModifierForForge(scripts.Script):
|
||||
sorting_priority = 15
|
||||
|
||||
def title(self):
|
||||
return "LatentModifier Integrated"
|
||||
|
||||
def show(self, is_img2img):
|
||||
# make this extension visible in both txt2img and img2img tab.
|
||||
return scripts.AlwaysVisible
|
||||
|
||||
def ui(self, *args, **kwargs):
|
||||
with gr.Accordion(open=False, label=self.title()):
|
||||
enabled = gr.Checkbox(label='Enabled', value=False)
|
||||
sharpness_multiplier = gr.Slider(label='Sharpness Multiplier', minimum=-100.0, maximum=100.0, step=0.1,
|
||||
value=0.0)
|
||||
sharpness_method = gr.Radio(label='Sharpness Method',
|
||||
choices=['anisotropic', 'joint-anisotropic', 'gaussian', 'cas'],
|
||||
value='anisotropic')
|
||||
tonemap_multiplier = gr.Slider(label='Tonemap Multiplier', minimum=0.0, maximum=100.0, step=0.01, value=0.0)
|
||||
tonemap_method = gr.Radio(label='Tonemap Method',
|
||||
choices=['reinhard', 'reinhard_perchannel', 'arctan', 'quantile', 'gated',
|
||||
'cfg-mimic', 'spatial-norm'], value='reinhard')
|
||||
tonemap_percentile = gr.Slider(label='Tonemap Percentile', minimum=0.0, maximum=100.0, step=0.005,
|
||||
value=100.0)
|
||||
contrast_multiplier = gr.Slider(label='Contrast Multiplier', minimum=-100.0, maximum=100.0, step=0.1,
|
||||
value=0.0)
|
||||
combat_method = gr.Radio(label='Combat Method',
|
||||
choices=['subtract', 'subtract_channels', 'subtract_median', 'sharpen'],
|
||||
value='subtract')
|
||||
combat_cfg_drift = gr.Slider(label='Combat Cfg Drift', minimum=-10.0, maximum=10.0, step=0.01, value=0.0)
|
||||
rescale_cfg_phi = gr.Slider(label='Rescale Cfg Phi', minimum=-10.0, maximum=10.0, step=0.01, value=0.0)
|
||||
extra_noise_type = gr.Radio(label='Extra Noise Type',
|
||||
choices=['gaussian', 'uniform', 'perlin', 'pink', 'green', 'pyramid'],
|
||||
value='gaussian')
|
||||
extra_noise_method = gr.Radio(label='Extra Noise Method',
|
||||
choices=['add', 'add_scaled', 'speckle', 'cads', 'cads_rescaled',
|
||||
'cads_speckle', 'cads_speckle_rescaled'], value='add')
|
||||
extra_noise_multiplier = gr.Slider(label='Extra Noise Multiplier', minimum=0.0, maximum=100.0, step=0.1,
|
||||
value=0.0)
|
||||
extra_noise_lowpass = gr.Slider(label='Extra Noise Lowpass', minimum=0, maximum=1000, step=1, value=100)
|
||||
divisive_norm_size = gr.Slider(label='Divisive Norm Size', minimum=1, maximum=255, step=1, value=127)
|
||||
divisive_norm_multiplier = gr.Slider(label='Divisive Norm Multiplier', minimum=0.0, maximum=1.0, step=0.01,
|
||||
value=0.0)
|
||||
spectral_mod_mode = gr.Radio(label='Spectral Mod Mode', choices=['hard_clamp', 'soft_clamp'],
|
||||
value='hard_clamp')
|
||||
spectral_mod_percentile = gr.Slider(label='Spectral Mod Percentile', minimum=0.0, maximum=50.0, step=0.01,
|
||||
value=5.0)
|
||||
spectral_mod_multiplier = gr.Slider(label='Spectral Mod Multiplier', minimum=-15.0, maximum=15.0, step=0.01,
|
||||
value=0.0)
|
||||
affect_uncond = gr.Radio(label='Affect Uncond', choices=['None', 'Sharpness'], value='None')
|
||||
dyn_cfg_augmentation = gr.Radio(label='Dyn Cfg Augmentation',
|
||||
choices=['None', 'dyncfg-halfcosine', 'dyncfg-halfcosine-mimic'],
|
||||
value='None')
|
||||
|
||||
return enabled, sharpness_multiplier, sharpness_method, tonemap_multiplier, tonemap_method, tonemap_percentile, contrast_multiplier, combat_method, combat_cfg_drift, rescale_cfg_phi, extra_noise_type, extra_noise_method, extra_noise_multiplier, extra_noise_lowpass, divisive_norm_size, divisive_norm_multiplier, spectral_mod_mode, spectral_mod_percentile, spectral_mod_multiplier, affect_uncond, dyn_cfg_augmentation
|
||||
|
||||
def process_before_every_sampling(self, p, *script_args, **kwargs):
|
||||
# This will be called before every sampling.
|
||||
# If you use highres fix, this will be called twice.
|
||||
|
||||
enabled, sharpness_multiplier, sharpness_method, tonemap_multiplier, tonemap_method, tonemap_percentile, contrast_multiplier, combat_method, combat_cfg_drift, rescale_cfg_phi, extra_noise_type, extra_noise_method, extra_noise_multiplier, extra_noise_lowpass, divisive_norm_size, divisive_norm_multiplier, spectral_mod_mode, spectral_mod_percentile, spectral_mod_multiplier, affect_uncond, dyn_cfg_augmentation = script_args
|
||||
|
||||
if not enabled:
|
||||
return
|
||||
|
||||
unet = p.sd_model.forge_objects.unet
|
||||
|
||||
unet = opModelSamplerLatentMegaModifier(unet, sharpness_multiplier, sharpness_method, tonemap_multiplier, tonemap_method, tonemap_percentile, contrast_multiplier, combat_method, combat_cfg_drift, rescale_cfg_phi, extra_noise_type, extra_noise_method, extra_noise_multiplier, extra_noise_lowpass, divisive_norm_size, divisive_norm_multiplier, spectral_mod_mode, spectral_mod_percentile, spectral_mod_multiplier, affect_uncond, dyn_cfg_augmentation, seed=p.seeds[0])[0]
|
||||
|
||||
p.sd_model.forge_objects.unet = unet
|
||||
|
||||
# Below codes will add some logs to the texts below the image outputs on UI.
|
||||
# The extra_generation_params does not influence results.
|
||||
p.extra_generation_params.update(dict(
|
||||
latent_modifier_enabled=enabled,
|
||||
latent_modifier_sharpness_multiplier=sharpness_multiplier,
|
||||
latent_modifier_sharpness_method=sharpness_method,
|
||||
latent_modifier_tonemap_multiplier=tonemap_multiplier,
|
||||
latent_modifier_tonemap_method=tonemap_method,
|
||||
latent_modifier_tonemap_percentile=tonemap_percentile,
|
||||
latent_modifier_contrast_multiplier=contrast_multiplier,
|
||||
latent_modifier_combat_method=combat_method,
|
||||
latent_modifier_combat_cfg_drift=combat_cfg_drift,
|
||||
latent_modifier_rescale_cfg_phi=rescale_cfg_phi,
|
||||
latent_modifier_extra_noise_type=extra_noise_type,
|
||||
latent_modifier_extra_noise_method=extra_noise_method,
|
||||
latent_modifier_extra_noise_multiplier=extra_noise_multiplier,
|
||||
latent_modifier_extra_noise_lowpass=extra_noise_lowpass,
|
||||
latent_modifier_divisive_norm_size=divisive_norm_size,
|
||||
latent_modifier_divisive_norm_multiplier=divisive_norm_multiplier,
|
||||
latent_modifier_spectral_mod_mode=spectral_mod_mode,
|
||||
latent_modifier_spectral_mod_percentile=spectral_mod_percentile,
|
||||
latent_modifier_spectral_mod_multiplier=spectral_mod_multiplier,
|
||||
latent_modifier_affect_uncond=affect_uncond,
|
||||
latent_modifier_dyn_cfg_augmentation=dyn_cfg_augmentation,
|
||||
))
|
||||
|
||||
return
|
||||
@@ -0,0 +1,616 @@
|
||||
# Tiled Diffusion
|
||||
# 1st edit by https://github.com/pkuliyi2015/multidiffusion-upscaler-for-automatic1111
|
||||
# 2nd edit by https://github.com/shiimizu/ComfyUI-TiledDiffusion
|
||||
# 3rd edit by Forge Official
|
||||
|
||||
|
||||
from __future__ import division
|
||||
import torch
|
||||
from torch import Tensor
|
||||
import ldm_patched.modules.model_management
|
||||
from ldm_patched.modules.model_patcher import ModelPatcher
|
||||
import ldm_patched.modules.model_patcher
|
||||
from ldm_patched.modules.model_base import BaseModel
|
||||
from typing import List, Union, Tuple, Dict
|
||||
from ldm_patched.contrib.external import ImageScale
|
||||
import ldm_patched.modules.utils
|
||||
from ldm_patched.modules.controlnet import ControlNet, T2IAdapter
|
||||
|
||||
opt_C = 4
|
||||
opt_f = 8
|
||||
|
||||
def ceildiv(big, small):
|
||||
# Correct ceiling division that avoids floating-point errors and importing math.ceil.
|
||||
return -(big // -small)
|
||||
|
||||
from enum import Enum
|
||||
class BlendMode(Enum): # i.e. LayerType
|
||||
FOREGROUND = 'Foreground'
|
||||
BACKGROUND = 'Background'
|
||||
|
||||
class Processing: ...
|
||||
class Device: ...
|
||||
devices = Device()
|
||||
devices.device = ldm_patched.modules.model_management.get_torch_device()
|
||||
|
||||
def null_decorator(fn):
|
||||
def wrapper(*args, **kwargs):
|
||||
return fn(*args, **kwargs)
|
||||
return wrapper
|
||||
|
||||
keep_signature = null_decorator
|
||||
controlnet = null_decorator
|
||||
stablesr = null_decorator
|
||||
grid_bbox = null_decorator
|
||||
custom_bbox = null_decorator
|
||||
noise_inverse = null_decorator
|
||||
|
||||
class BBox:
|
||||
''' grid bbox '''
|
||||
|
||||
def __init__(self, x:int, y:int, w:int, h:int):
|
||||
self.x = x
|
||||
self.y = y
|
||||
self.w = w
|
||||
self.h = h
|
||||
self.box = [x, y, x+w, y+h]
|
||||
self.slicer = slice(None), slice(None), slice(y, y+h), slice(x, x+w)
|
||||
|
||||
def __getitem__(self, idx:int) -> int:
|
||||
return self.box[idx]
|
||||
|
||||
def split_bboxes(w:int, h:int, tile_w:int, tile_h:int, overlap:int=16, init_weight:Union[Tensor, float]=1.0) -> Tuple[List[BBox], Tensor]:
|
||||
cols = ceildiv((w - overlap) , (tile_w - overlap))
|
||||
rows = ceildiv((h - overlap) , (tile_h - overlap))
|
||||
dx = (w - tile_w) / (cols - 1) if cols > 1 else 0
|
||||
dy = (h - tile_h) / (rows - 1) if rows > 1 else 0
|
||||
|
||||
bbox_list: List[BBox] = []
|
||||
weight = torch.zeros((1, 1, h, w), device=devices.device, dtype=torch.float32)
|
||||
for row in range(rows):
|
||||
y = min(int(row * dy), h - tile_h)
|
||||
for col in range(cols):
|
||||
x = min(int(col * dx), w - tile_w)
|
||||
|
||||
bbox = BBox(x, y, tile_w, tile_h)
|
||||
bbox_list.append(bbox)
|
||||
weight[bbox.slicer] += init_weight
|
||||
|
||||
return bbox_list, weight
|
||||
|
||||
class CustomBBox(BBox):
|
||||
''' region control bbox '''
|
||||
pass
|
||||
|
||||
class AbstractDiffusion:
|
||||
def __init__(self):
|
||||
self.method = self.__class__.__name__
|
||||
self.pbar = None
|
||||
|
||||
|
||||
self.w: int = 0
|
||||
self.h: int = 0
|
||||
self.tile_width: int = None
|
||||
self.tile_height: int = None
|
||||
self.tile_overlap: int = None
|
||||
self.tile_batch_size: int = None
|
||||
|
||||
# cache. final result of current sampling step, [B, C=4, H//8, W//8]
|
||||
# avoiding overhead of creating new tensors and weight summing
|
||||
self.x_buffer: Tensor = None
|
||||
# self.w: int = int(self.p.width // opt_f) # latent size
|
||||
# self.h: int = int(self.p.height // opt_f)
|
||||
# weights for background & grid bboxes
|
||||
self._weights: Tensor = None
|
||||
# self.weights: Tensor = torch.zeros((1, 1, self.h, self.w), device=devices.device, dtype=torch.float32)
|
||||
self._init_grid_bbox = None
|
||||
self._init_done = None
|
||||
|
||||
# count the step correctly
|
||||
self.step_count = 0
|
||||
self.inner_loop_count = 0
|
||||
self.kdiff_step = -1
|
||||
|
||||
# ext. Grid tiling painting (grid bbox)
|
||||
self.enable_grid_bbox: bool = False
|
||||
self.tile_w: int = None
|
||||
self.tile_h: int = None
|
||||
self.tile_bs: int = None
|
||||
self.num_tiles: int = None
|
||||
self.num_batches: int = None
|
||||
self.batched_bboxes: List[List[BBox]] = []
|
||||
|
||||
# ext. Region Prompt Control (custom bbox)
|
||||
self.enable_custom_bbox: bool = False
|
||||
self.custom_bboxes: List[CustomBBox] = []
|
||||
# self.cond_basis: Cond = None
|
||||
# self.uncond_basis: Uncond = None
|
||||
# self.draw_background: bool = True # by default we draw major prompts in grid tiles
|
||||
# self.causal_layers: bool = None
|
||||
|
||||
# ext. ControlNet
|
||||
self.enable_controlnet: bool = False
|
||||
# self.controlnet_script: ModuleType = None
|
||||
self.control_tensor_batch_dict = {}
|
||||
self.control_tensor_batch: List[List[Tensor]] = [[]]
|
||||
# self.control_params: Dict[str, Tensor] = None # {}
|
||||
self.control_params: Dict[Tuple, List[List[Tensor]]] = {}
|
||||
self.control_tensor_cpu: bool = None
|
||||
self.control_tensor_custom: List[List[Tensor]] = []
|
||||
|
||||
self.draw_background: bool = True # by default we draw major prompts in grid tiles
|
||||
self.control_tensor_cpu = False
|
||||
self.weights = None
|
||||
self.imagescale = ImageScale()
|
||||
|
||||
def reset(self):
|
||||
tile_width = self.tile_width
|
||||
tile_height = self.tile_height
|
||||
tile_overlap = self.tile_overlap
|
||||
tile_batch_size = self.tile_batch_size
|
||||
self.__init__()
|
||||
self.tile_width = tile_width
|
||||
self.tile_height = tile_height
|
||||
self.tile_overlap = tile_overlap
|
||||
self.tile_batch_size = tile_batch_size
|
||||
|
||||
def repeat_tensor(self, x:Tensor, n:int, concat=False, concat_to=0) -> Tensor:
|
||||
''' repeat the tensor on it's first dim '''
|
||||
if n == 1: return x
|
||||
B = x.shape[0]
|
||||
r_dims = len(x.shape) - 1
|
||||
if B == 1: # batch_size = 1 (not `tile_batch_size`)
|
||||
shape = [n] + [-1] * r_dims # [N, -1, ...]
|
||||
return x.expand(shape) # `expand` is much lighter than `tile`
|
||||
else:
|
||||
if concat:
|
||||
return torch.cat([x for _ in range(n)], dim=0)[:concat_to]
|
||||
shape = [n] + [1] * r_dims # [N, 1, ...]
|
||||
return x.repeat(shape)
|
||||
def update_pbar(self):
|
||||
if self.pbar.n >= self.pbar.total:
|
||||
self.pbar.close()
|
||||
else:
|
||||
# self.pbar.update()
|
||||
sampling_step = 20
|
||||
if self.step_count == sampling_step:
|
||||
self.inner_loop_count += 1
|
||||
if self.inner_loop_count < self.total_bboxes:
|
||||
self.pbar.update()
|
||||
else:
|
||||
self.step_count = sampling_step
|
||||
self.inner_loop_count = 0
|
||||
def reset_buffer(self, x_in:Tensor):
|
||||
# Judge if the shape of x_in is the same as the shape of x_buffer
|
||||
if self.x_buffer is None or self.x_buffer.shape != x_in.shape:
|
||||
self.x_buffer = torch.zeros_like(x_in, device=x_in.device, dtype=x_in.dtype)
|
||||
else:
|
||||
self.x_buffer.zero_()
|
||||
|
||||
@grid_bbox
|
||||
def init_grid_bbox(self, tile_w:int, tile_h:int, overlap:int, tile_bs:int):
|
||||
# if self._init_grid_bbox is not None: return
|
||||
# self._init_grid_bbox = True
|
||||
self.weights = torch.zeros((1, 1, self.h, self.w), device=devices.device, dtype=torch.float32)
|
||||
self.enable_grid_bbox = True
|
||||
|
||||
self.tile_w = min(tile_w, self.w)
|
||||
self.tile_h = min(tile_h, self.h)
|
||||
overlap = max(0, min(overlap, min(tile_w, tile_h) - 4))
|
||||
# split the latent into overlapped tiles, then batching
|
||||
# weights basically indicate how many times a pixel is painted
|
||||
bboxes, weights = split_bboxes(self.w, self.h, self.tile_w, self.tile_h, overlap, self.get_tile_weights())
|
||||
self.weights += weights
|
||||
self.num_tiles = len(bboxes)
|
||||
self.num_batches = ceildiv(self.num_tiles , tile_bs)
|
||||
self.tile_bs = ceildiv(len(bboxes) , self.num_batches) # optimal_batch_size
|
||||
self.batched_bboxes = [bboxes[i*self.tile_bs:(i+1)*self.tile_bs] for i in range(self.num_batches)]
|
||||
|
||||
@grid_bbox
|
||||
def get_tile_weights(self) -> Union[Tensor, float]:
|
||||
return 1.0
|
||||
|
||||
@noise_inverse
|
||||
def init_noise_inverse(self, steps:int, retouch:float, get_cache_callback, set_cache_callback, renoise_strength:float, renoise_kernel:int):
|
||||
self.noise_inverse_enabled = True
|
||||
self.noise_inverse_steps = steps
|
||||
self.noise_inverse_retouch = float(retouch)
|
||||
self.noise_inverse_renoise_strength = float(renoise_strength)
|
||||
self.noise_inverse_renoise_kernel = int(renoise_kernel)
|
||||
self.noise_inverse_set_cache = set_cache_callback
|
||||
self.noise_inverse_get_cache = get_cache_callback
|
||||
|
||||
def init_done(self):
|
||||
'''
|
||||
Call this after all `init_*`, settings are done, now perform:
|
||||
- settings sanity check
|
||||
- pre-computations, cache init
|
||||
- anything thing needed before denoising starts
|
||||
'''
|
||||
|
||||
# if self._init_done is not None: return
|
||||
# self._init_done = True
|
||||
self.total_bboxes = 0
|
||||
if self.enable_grid_bbox: self.total_bboxes += self.num_batches
|
||||
if self.enable_custom_bbox: self.total_bboxes += len(self.custom_bboxes)
|
||||
assert self.total_bboxes > 0, "Nothing to paint! No background to draw and no custom bboxes were provided."
|
||||
|
||||
# sampling_steps = _steps
|
||||
# self.pbar = tqdm(total=(self.total_bboxes) * sampling_steps, desc=f"{self.method} Sampling: ")
|
||||
|
||||
@controlnet
|
||||
def prepare_controlnet_tensors(self, refresh:bool=False, tensor=None):
|
||||
''' Crop the control tensor into tiles and cache them '''
|
||||
if not refresh:
|
||||
if self.control_tensor_batch is not None or self.control_params is not None: return
|
||||
tensors = [tensor]
|
||||
self.org_control_tensor_batch = tensors
|
||||
self.control_tensor_batch = []
|
||||
for i in range(len(tensors)):
|
||||
control_tile_list = []
|
||||
control_tensor = tensors[i]
|
||||
for bboxes in self.batched_bboxes:
|
||||
single_batch_tensors = []
|
||||
for bbox in bboxes:
|
||||
if len(control_tensor.shape) == 3:
|
||||
control_tensor.unsqueeze_(0)
|
||||
control_tile = control_tensor[:, :, bbox[1]*opt_f:bbox[3]*opt_f, bbox[0]*opt_f:bbox[2]*opt_f]
|
||||
single_batch_tensors.append(control_tile)
|
||||
control_tile = torch.cat(single_batch_tensors, dim=0)
|
||||
if self.control_tensor_cpu:
|
||||
control_tile = control_tile.cpu()
|
||||
control_tile_list.append(control_tile)
|
||||
self.control_tensor_batch.append(control_tile_list)
|
||||
|
||||
if len(self.custom_bboxes) > 0:
|
||||
custom_control_tile_list = []
|
||||
for bbox in self.custom_bboxes:
|
||||
if len(control_tensor.shape) == 3:
|
||||
control_tensor.unsqueeze_(0)
|
||||
control_tile = control_tensor[:, :, bbox[1]*opt_f:bbox[3]*opt_f, bbox[0]*opt_f:bbox[2]*opt_f]
|
||||
if self.control_tensor_cpu:
|
||||
control_tile = control_tile.cpu()
|
||||
custom_control_tile_list.append(control_tile)
|
||||
self.control_tensor_custom.append(custom_control_tile_list)
|
||||
|
||||
@controlnet
|
||||
def switch_controlnet_tensors(self, batch_id:int, x_batch_size:int, tile_batch_size:int, is_denoise=False):
|
||||
# if not self.enable_controlnet: return
|
||||
if self.control_tensor_batch is None: return
|
||||
# self.control_params = [0]
|
||||
|
||||
# for param_id in range(len(self.control_params)):
|
||||
for param_id in range(len(self.control_tensor_batch)):
|
||||
# tensor that was concatenated in `prepare_controlnet_tensors`
|
||||
control_tile = self.control_tensor_batch[param_id][batch_id]
|
||||
# broadcast to latent batch size
|
||||
if x_batch_size > 1: # self.is_kdiff:
|
||||
all_control_tile = []
|
||||
for i in range(tile_batch_size):
|
||||
this_control_tile = [control_tile[i].unsqueeze(0)] * x_batch_size
|
||||
all_control_tile.append(torch.cat(this_control_tile, dim=0))
|
||||
control_tile = torch.cat(all_control_tile, dim=0) # [:x_tile.shape[0]]
|
||||
self.control_tensor_batch[param_id][batch_id] = control_tile
|
||||
# else:
|
||||
# control_tile = control_tile.repeat([x_batch_size if is_denoise else x_batch_size * 2, 1, 1, 1])
|
||||
# self.control_params[param_id].hint_cond = control_tile.to(devices.device)
|
||||
|
||||
def process_controlnet(self, x_shape, x_dtype, c_in: dict, cond_or_uncond: List, bboxes, batch_size: int, batch_id: int):
|
||||
control: ControlNet = c_in['control_model']
|
||||
param_id = -1 # current controlnet & previous_controlnets
|
||||
tuple_key = tuple(cond_or_uncond) + tuple(x_shape)
|
||||
while control is not None:
|
||||
param_id += 1
|
||||
PH, PW = self.h*8, self.w*8
|
||||
|
||||
if self.control_params.get(tuple_key, None) is None:
|
||||
self.control_params[tuple_key] = [[None]]
|
||||
val = self.control_params[tuple_key]
|
||||
if param_id+1 >= len(val):
|
||||
val.extend([[None] for _ in range(param_id+1)])
|
||||
if len(self.batched_bboxes) >= len(val[param_id]):
|
||||
val[param_id].extend([[None] for _ in range(len(self.batched_bboxes))])
|
||||
|
||||
# Below is taken from ldm_patched.modules.controlnet.py, but we need to additionally tile the cnets.
|
||||
# if statement: eager eval. first time when cond_hint is None.
|
||||
if self.refresh or control.cond_hint is None or not isinstance(self.control_params[tuple_key][param_id][batch_id], Tensor):
|
||||
dtype = getattr(control, 'manual_cast_dtype', None)
|
||||
if dtype is None: dtype = getattr(getattr(control, 'control_model', None), 'dtype', None)
|
||||
if dtype is None: dtype = x_dtype
|
||||
if isinstance(control, T2IAdapter):
|
||||
width, height = control.scale_image_to(PW, PH)
|
||||
control.cond_hint = ldm_patched.modules.utils.common_upscale(control.cond_hint_original, width, height, 'nearest-exact', "center").float().to(control.device)
|
||||
if control.channels_in == 1 and control.cond_hint.shape[1] > 1:
|
||||
control.cond_hint = torch.mean(control.cond_hint, 1, keepdim=True)
|
||||
elif control.__class__.__name__ == 'ControlLLLiteAdvanced':
|
||||
if control.sub_idxs is not None and control.cond_hint_original.shape[0] >= control.full_latent_length:
|
||||
control.cond_hint = ldm_patched.modules.utils.common_upscale(control.cond_hint_original[control.sub_idxs], PW, PH, 'nearest-exact', "center").to(dtype=dtype, device=control.device)
|
||||
else:
|
||||
if (PH, PW) == (control.cond_hint_original.shape[-2], control.cond_hint_original.shape[-1]):
|
||||
control.cond_hint = control.cond_hint_original.clone().to(dtype=dtype, device=control.device)
|
||||
else:
|
||||
control.cond_hint = ldm_patched.modules.utils.common_upscale(control.cond_hint_original, PW, PH, 'nearest-exact', "center").to(dtype=dtype, device=control.device)
|
||||
else:
|
||||
if (PH, PW) == (control.cond_hint_original.shape[-2], control.cond_hint_original.shape[-1]):
|
||||
control.cond_hint = control.cond_hint_original.clone().to(dtype=dtype, device=control.device)
|
||||
else:
|
||||
control.cond_hint = ldm_patched.modules.utils.common_upscale(control.cond_hint_original, PW, PH, 'nearest-exact', 'center').to(dtype=dtype, device=control.device)
|
||||
|
||||
# Broadcast then tile
|
||||
#
|
||||
# Below can be in the parent's if clause because self.refresh will trigger on resolution change, e.g. cause of ConditioningSetArea
|
||||
# so that particular case isn't cached atm.
|
||||
cond_hint_pre_tile = control.cond_hint
|
||||
if control.cond_hint.shape[0] < batch_size :
|
||||
cond_hint_pre_tile = self.repeat_tensor(control.cond_hint, ceildiv(batch_size, control.cond_hint.shape[0]))[:batch_size]
|
||||
cns = [cond_hint_pre_tile[:, :, bbox[1]*opt_f:bbox[3]*opt_f, bbox[0]*opt_f:bbox[2]*opt_f] for bbox in bboxes]
|
||||
control.cond_hint = torch.cat(cns, dim=0)
|
||||
self.control_params[tuple_key][param_id][batch_id]=control.cond_hint
|
||||
else:
|
||||
control.cond_hint = self.control_params[tuple_key][param_id][batch_id]
|
||||
control = control.previous_controlnet
|
||||
|
||||
import numpy as np
|
||||
from numpy import pi, exp, sqrt
|
||||
def gaussian_weights(tile_w:int, tile_h:int) -> Tensor:
|
||||
'''
|
||||
Copy from the original implementation of Mixture of Diffusers
|
||||
https://github.com/albarji/mixture-of-diffusers/blob/master/mixdiff/tiling.py
|
||||
This generates gaussian weights to smooth the noise of each tile.
|
||||
This is critical for this method to work.
|
||||
'''
|
||||
f = lambda x, midpoint, var=0.01: exp(-(x-midpoint)*(x-midpoint) / (tile_w*tile_w) / (2*var)) / sqrt(2*pi*var)
|
||||
x_probs = [f(x, (tile_w - 1) / 2) for x in range(tile_w)] # -1 because index goes from 0 to latent_width - 1
|
||||
y_probs = [f(y, tile_h / 2) for y in range(tile_h)]
|
||||
|
||||
w = np.outer(y_probs, x_probs)
|
||||
return torch.from_numpy(w).to(devices.device, dtype=torch.float32)
|
||||
|
||||
class CondDict: ...
|
||||
|
||||
class MultiDiffusion(AbstractDiffusion):
|
||||
|
||||
@torch.no_grad()
|
||||
def __call__(self, model_function: BaseModel.apply_model, args: dict):
|
||||
x_in: Tensor = args["input"]
|
||||
t_in: Tensor = args["timestep"]
|
||||
c_in: dict = args["c"]
|
||||
cond_or_uncond: List = args["cond_or_uncond"]
|
||||
c_crossattn: Tensor = c_in['c_crossattn']
|
||||
|
||||
N, C, H, W = x_in.shape
|
||||
|
||||
# ldm_patched.modulesui can feed in a latent that's a different size cause of SetArea, so we'll refresh in that case.
|
||||
self.refresh = False
|
||||
if self.weights is None or self.h != H or self.w != W:
|
||||
self.h, self.w = H, W
|
||||
self.refresh = True
|
||||
self.init_grid_bbox(self.tile_width, self.tile_height, self.tile_overlap, self.tile_batch_size)
|
||||
# init everything done, perform sanity check & pre-computations
|
||||
self.init_done()
|
||||
self.h, self.w = H, W
|
||||
# clear buffer canvas
|
||||
self.reset_buffer(x_in)
|
||||
|
||||
# Background sampling (grid bbox)
|
||||
if self.draw_background:
|
||||
for batch_id, bboxes in enumerate(self.batched_bboxes):
|
||||
if ldm_patched.modules.model_management.processing_interrupted():
|
||||
# self.pbar.close()
|
||||
return x_in
|
||||
|
||||
# batching & compute tiles
|
||||
x_tile = torch.cat([x_in[bbox.slicer] for bbox in bboxes], dim=0) # [TB, C, TH, TW]
|
||||
n_rep = len(bboxes)
|
||||
ts_tile = self.repeat_tensor(t_in, n_rep)
|
||||
cond_tile = self.repeat_tensor(c_crossattn, n_rep)
|
||||
c_tile = c_in.copy()
|
||||
c_tile['c_crossattn'] = cond_tile
|
||||
if 'time_context' in c_in:
|
||||
c_tile['time_context'] = self.repeat_tensor(c_in['time_context'], n_rep)
|
||||
for key in c_tile:
|
||||
if key in ['y', 'c_concat']:
|
||||
icond = c_tile[key]
|
||||
if icond.shape[2:] == (self.h, self.w):
|
||||
c_tile[key] = torch.cat([icond[bbox.slicer] for bbox in bboxes])
|
||||
else:
|
||||
c_tile[key] = self.repeat_tensor(icond, n_rep)
|
||||
|
||||
# controlnet tiling
|
||||
# self.switch_controlnet_tensors(batch_id, N, len(bboxes))
|
||||
if 'control' in c_in:
|
||||
self.process_controlnet(x_tile.shape, x_tile.dtype, c_in, cond_or_uncond, bboxes, N, batch_id)
|
||||
c_tile['control'] = c_in['control_model'].get_control(x_tile, ts_tile, c_tile, len(cond_or_uncond))
|
||||
|
||||
# stablesr tiling
|
||||
# self.switch_stablesr_tensors(batch_id)
|
||||
|
||||
x_tile_out = model_function(x_tile, ts_tile, **c_tile)
|
||||
|
||||
for i, bbox in enumerate(bboxes):
|
||||
self.x_buffer[bbox.slicer] += x_tile_out[i*N:(i+1)*N, :, :, :]
|
||||
del x_tile_out, x_tile, ts_tile, c_tile
|
||||
|
||||
# update progress bar
|
||||
# self.update_pbar()
|
||||
|
||||
# Averaging background buffer
|
||||
x_out = torch.where(self.weights > 1, self.x_buffer / self.weights, self.x_buffer)
|
||||
|
||||
return x_out
|
||||
|
||||
class MixtureOfDiffusers(AbstractDiffusion):
|
||||
"""
|
||||
Mixture-of-Diffusers Implementation
|
||||
https://github.com/albarji/mixture-of-diffusers
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
# weights for custom bboxes
|
||||
self.custom_weights: List[Tensor] = []
|
||||
self.get_weight = gaussian_weights
|
||||
|
||||
def init_done(self):
|
||||
super().init_done()
|
||||
# The original gaussian weights can be extremely small, so we rescale them for numerical stability
|
||||
self.rescale_factor = 1 / self.weights
|
||||
# Meanwhile, we rescale the custom weights in advance to save time of slicing
|
||||
for bbox_id, bbox in enumerate(self.custom_bboxes):
|
||||
if bbox.blend_mode == BlendMode.BACKGROUND:
|
||||
self.custom_weights[bbox_id] *= self.rescale_factor[bbox.slicer]
|
||||
|
||||
@grid_bbox
|
||||
def get_tile_weights(self) -> Tensor:
|
||||
# weights for grid bboxes
|
||||
# if not hasattr(self, 'tile_weights'):
|
||||
# x_in can change sizes cause of ConditioningSetArea, so we have to recalcualte each time
|
||||
self.tile_weights = self.get_weight(self.tile_w, self.tile_h)
|
||||
return self.tile_weights
|
||||
|
||||
@torch.no_grad()
|
||||
def __call__(self, model_function: BaseModel.apply_model, args: dict):
|
||||
x_in: Tensor = args["input"]
|
||||
t_in: Tensor = args["timestep"]
|
||||
c_in: dict = args["c"]
|
||||
cond_or_uncond: List= args["cond_or_uncond"]
|
||||
c_crossattn: Tensor = c_in['c_crossattn']
|
||||
|
||||
N, C, H, W = x_in.shape
|
||||
|
||||
self.refresh = False
|
||||
# self.refresh = True
|
||||
if self.weights is None or self.h != H or self.w != W:
|
||||
self.h, self.w = H, W
|
||||
self.refresh = True
|
||||
self.init_grid_bbox(self.tile_width, self.tile_height, self.tile_overlap, self.tile_batch_size)
|
||||
# init everything done, perform sanity check & pre-computations
|
||||
self.init_done()
|
||||
self.h, self.w = H, W
|
||||
# clear buffer canvas
|
||||
self.reset_buffer(x_in)
|
||||
|
||||
# self.pbar = tqdm(total=(self.total_bboxes) * sampling_steps, desc=f"{self.method} Sampling: ")
|
||||
# self.pbar = tqdm(total=len(self.batched_bboxes), desc=f"{self.method} Sampling: ")
|
||||
|
||||
# Global sampling
|
||||
if self.draw_background:
|
||||
for batch_id, bboxes in enumerate(self.batched_bboxes): # batch_id is the `Latent tile batch size`
|
||||
if ldm_patched.modules.model_management.processing_interrupted():
|
||||
# self.pbar.close()
|
||||
return x_in
|
||||
|
||||
# batching
|
||||
x_tile_list = []
|
||||
t_tile_list = []
|
||||
icond_map = {}
|
||||
# tcond_tile_list = []
|
||||
# icond_tile_list = []
|
||||
# vcond_tile_list = []
|
||||
# control_list = []
|
||||
for bbox in bboxes:
|
||||
x_tile_list.append(x_in[bbox.slicer])
|
||||
t_tile_list.append(t_in)
|
||||
if isinstance(c_in, dict):
|
||||
# tcond
|
||||
# tcond_tile = c_crossattn #self.get_tcond(c_in) # cond, [1, 77, 768]
|
||||
# tcond_tile_list.append(tcond_tile)
|
||||
# present in sdxl
|
||||
for key in ['y', 'c_concat']:
|
||||
if key in c_in:
|
||||
icond=c_in[key] # self.get_icond(c_in)
|
||||
if icond.shape[2:] == (self.h, self.w):
|
||||
icond = icond[bbox.slicer]
|
||||
if icond_map.get(key, None) is None:
|
||||
icond_map[key] = []
|
||||
icond_map[key].append(icond)
|
||||
# # vcond:
|
||||
# vcond = self.get_vcond(c_in)
|
||||
# vcond_tile_list.append(vcond)
|
||||
else:
|
||||
print('>> [WARN] not supported, make an issue on github!!')
|
||||
n_rep = len(bboxes)
|
||||
x_tile = torch.cat(x_tile_list, dim=0) # differs each
|
||||
t_tile = self.repeat_tensor(t_in, n_rep) # just repeat
|
||||
tcond_tile = self.repeat_tensor(c_crossattn, n_rep) # just repeat
|
||||
c_tile = c_in.copy()
|
||||
c_tile['c_crossattn'] = tcond_tile
|
||||
if 'time_context' in c_in:
|
||||
c_tile['time_context'] = self.repeat_tensor(c_in['time_context'], n_rep) # just repeat
|
||||
for key in c_tile:
|
||||
if key in ['y', 'c_concat']:
|
||||
icond_tile = torch.cat(icond_map[key], dim=0) # differs each
|
||||
c_tile[key] = icond_tile
|
||||
# vcond_tile = torch.cat(vcond_tile_list, dim=0) if None not in vcond_tile_list else None # just repeat
|
||||
|
||||
# controlnet
|
||||
# self.switch_controlnet_tensors(batch_id, N, len(bboxes), is_denoise=True)
|
||||
if 'control' in c_in:
|
||||
control=c_in['control']
|
||||
self.process_controlnet(x_tile.shape, x_tile.dtype, c_in, cond_or_uncond, bboxes, N, batch_id)
|
||||
c_tile['control'] = control.get_control(x_tile, t_tile, c_tile, len(cond_or_uncond))
|
||||
|
||||
# stablesr
|
||||
# self.switch_stablesr_tensors(batch_id)
|
||||
|
||||
# denoising: here the x is the noise
|
||||
x_tile_out = model_function(x_tile, t_tile, **c_tile)
|
||||
|
||||
# de-batching
|
||||
for i, bbox in enumerate(bboxes):
|
||||
# These weights can be calcluated in advance, but will cost a lot of vram
|
||||
# when you have many tiles. So we calculate it here.
|
||||
w = self.tile_weights * self.rescale_factor[bbox.slicer]
|
||||
self.x_buffer[bbox.slicer] += x_tile_out[i*N:(i+1)*N, :, :, :] * w
|
||||
del x_tile_out, x_tile, t_tile, c_tile
|
||||
|
||||
# self.update_pbar()
|
||||
# self.pbar.update()
|
||||
# self.pbar.close()
|
||||
x_out = self.x_buffer
|
||||
|
||||
return x_out
|
||||
|
||||
|
||||
MAX_RESOLUTION=8192
|
||||
class TiledDiffusion():
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {"model": ("MODEL", ),
|
||||
"method": (["MultiDiffusion", "Mixture of Diffusers"], {"default": "Mixture of Diffusers"}),
|
||||
# "tile_width": ("INT", {"default": 96, "min": 16, "max": 256, "step": 16}),
|
||||
"tile_width": ("INT", {"default": 96*opt_f, "min": 16, "max": MAX_RESOLUTION, "step": 16}),
|
||||
# "tile_height": ("INT", {"default": 96, "min": 16, "max": 256, "step": 16}),
|
||||
"tile_height": ("INT", {"default": 96*opt_f, "min": 16, "max": MAX_RESOLUTION, "step": 16}),
|
||||
"tile_overlap": ("INT", {"default": 8*opt_f, "min": 0, "max": 256*opt_f, "step": 4*opt_f}),
|
||||
"tile_batch_size": ("INT", {"default": 4, "min": 1, "max": MAX_RESOLUTION, "step": 1}),
|
||||
}}
|
||||
RETURN_TYPES = ("MODEL",)
|
||||
FUNCTION = "apply"
|
||||
CATEGORY = "_for_testing"
|
||||
|
||||
def apply(self, model: ModelPatcher, method, tile_width, tile_height, tile_overlap, tile_batch_size):
|
||||
if method == "Mixture of Diffusers":
|
||||
implement = MixtureOfDiffusers()
|
||||
else:
|
||||
implement = MultiDiffusion()
|
||||
|
||||
# if noise_inversion:
|
||||
# get_cache_callback = self.noise_inverse_get_cache
|
||||
# set_cache_callback = None # lambda x0, xt, prompts: self.noise_inverse_set_cache(p, x0, xt, prompts, steps, retouch)
|
||||
# implement.init_noise_inverse(steps, retouch, get_cache_callback, set_cache_callback, renoise_strength, renoise_kernel_size)
|
||||
|
||||
implement.tile_width = tile_width // opt_f
|
||||
implement.tile_height = tile_height // opt_f
|
||||
implement.tile_overlap = tile_overlap // opt_f
|
||||
implement.tile_batch_size = tile_batch_size
|
||||
# implement.init_grid_bbox(tile_width, tile_height, tile_overlap, tile_batch_size)
|
||||
# # init everything done, perform sanity check & pre-computations
|
||||
# implement.init_done()
|
||||
# hijack the behaviours
|
||||
# implement.hook()
|
||||
model = model.clone()
|
||||
model.set_model_unet_function_wrapper(implement)
|
||||
model.model_options['tiled_diffusion'] = True
|
||||
return (model,)
|
||||
@@ -0,0 +1,58 @@
|
||||
import gradio as gr
|
||||
from modules import scripts
|
||||
|
||||
from lib_multidiffusion.tiled_diffusion import TiledDiffusion
|
||||
|
||||
|
||||
opTiledDiffusion = TiledDiffusion().apply
|
||||
|
||||
|
||||
class MultiDiffusionForForge(scripts.Script):
|
||||
sorting_priority = 16
|
||||
|
||||
def title(self):
|
||||
return "MultiDiffusion Integrated"
|
||||
|
||||
def show(self, is_img2img):
|
||||
# make this extension visible in both txt2img and img2img tab.
|
||||
return scripts.AlwaysVisible
|
||||
|
||||
def ui(self, *args, **kwargs):
|
||||
with gr.Accordion(open=False, label=self.title()):
|
||||
enabled = gr.Checkbox(label='Enabled', value=False)
|
||||
method = gr.Radio(label='Method', choices=['MultiDiffusion', 'Mixture of Diffusers'],
|
||||
value='MultiDiffusion')
|
||||
tile_width = gr.Slider(label='Tile Width', minimum=16, maximum=8192, step=16, value=768)
|
||||
tile_height = gr.Slider(label='Tile Height', minimum=16, maximum=8192, step=16, value=768)
|
||||
tile_overlap = gr.Slider(label='Tile Overlap', minimum=0, maximum=2048, step=32, value=64)
|
||||
tile_batch_size = gr.Slider(label='Tile Batch Size', minimum=1, maximum=8192, step=1, value=4)
|
||||
|
||||
return enabled, method, tile_width, tile_height, tile_overlap, tile_batch_size
|
||||
|
||||
def process_before_every_sampling(self, p, *script_args, **kwargs):
|
||||
# This will be called before every sampling.
|
||||
# If you use highres fix, this will be called twice.
|
||||
|
||||
enabled, method, tile_width, tile_height, tile_overlap, tile_batch_size = script_args
|
||||
|
||||
if not enabled:
|
||||
return
|
||||
|
||||
unet = p.sd_model.forge_objects.unet
|
||||
|
||||
unet = opTiledDiffusion(unet, method, tile_width, tile_height, tile_overlap, tile_batch_size)[0]
|
||||
|
||||
p.sd_model.forge_objects.unet = unet
|
||||
|
||||
# Below codes will add some logs to the texts below the image outputs on UI.
|
||||
# The extra_generation_params does not influence results.
|
||||
p.extra_generation_params.update(dict(
|
||||
multidiffusion_enabled=enabled,
|
||||
multidiffusion_method=method,
|
||||
multidiffusion_tile_width=tile_width,
|
||||
multidiffusion_tile_height=tile_height,
|
||||
multidiffusion_tile_overlap=tile_overlap,
|
||||
multidiffusion_tile_batch_size=tile_batch_size,
|
||||
))
|
||||
|
||||
return
|
||||
@@ -0,0 +1,47 @@
|
||||
import gradio as gr
|
||||
|
||||
from modules import scripts
|
||||
from ldm_patched.modules import model_management
|
||||
|
||||
|
||||
class NeverOOMForForge(scripts.Script):
|
||||
sorting_priority = 18
|
||||
|
||||
def __init__(self):
|
||||
self.previous_unet_enabled = False
|
||||
self.original_vram_state = model_management.vram_state
|
||||
|
||||
def title(self):
|
||||
return "Never OOM Integrated"
|
||||
|
||||
def show(self, is_img2img):
|
||||
return scripts.AlwaysVisible
|
||||
|
||||
def ui(self, *args, **kwargs):
|
||||
with gr.Accordion(open=False, label=self.title()):
|
||||
unet_enabled = gr.Checkbox(label='Enabled for UNet (always maximize offload)', value=False)
|
||||
vae_enabled = gr.Checkbox(label='Enabled for VAE (always tiled)', value=False)
|
||||
return unet_enabled, vae_enabled
|
||||
|
||||
def process(self, p, *script_args, **kwargs):
|
||||
unet_enabled, vae_enabled = script_args
|
||||
|
||||
if unet_enabled:
|
||||
print('NeverOOM Enabled for UNet (always maximize offload)')
|
||||
|
||||
if vae_enabled:
|
||||
print('NeverOOM Enabled for VAE (always tiled)')
|
||||
|
||||
model_management.VAE_ALWAYS_TILED = vae_enabled
|
||||
|
||||
if self.previous_unet_enabled != unet_enabled:
|
||||
model_management.unload_all_models()
|
||||
if unet_enabled:
|
||||
self.original_vram_state = model_management.vram_state
|
||||
model_management.vram_state = model_management.VRAMState.NO_VRAM
|
||||
else:
|
||||
model_management.vram_state = self.original_vram_state
|
||||
print(f'VARM State Changed To {model_management.vram_state.name}')
|
||||
self.previous_unet_enabled = unet_enabled
|
||||
|
||||
return
|
||||
@@ -8,6 +8,8 @@ opSelfAttentionGuidance = SelfAttentionGuidance()
|
||||
|
||||
|
||||
class SAGForForge(scripts.Script):
|
||||
sorting_priority = 12.5
|
||||
|
||||
def title(self):
|
||||
return "SelfAttentionGuidance Integrated"
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import torch
|
||||
import gradio as gr
|
||||
|
||||
from modules import scripts
|
||||
@@ -9,6 +10,8 @@ def sdp(q, k, v, transformer_options):
|
||||
|
||||
|
||||
class StyleAlignForForge(scripts.Script):
|
||||
sorting_priority = 17
|
||||
|
||||
def title(self):
|
||||
return "StyleAlign Integrated"
|
||||
|
||||
@@ -37,13 +40,33 @@ class StyleAlignForForge(scripts.Script):
|
||||
b, f, c = x.shape
|
||||
return x.reshape(1, b * f, c)
|
||||
|
||||
def attn1_proc(q, k, v, transformer_options):
|
||||
def aligned_attention(q, k, v, transformer_options):
|
||||
b, f, c = q.shape
|
||||
o = sdp(join(q), join(k), join(v), transformer_options)
|
||||
b2, f2, c2 = o.shape
|
||||
o = o.reshape(b, b2 * f2 // b, c2)
|
||||
return o
|
||||
|
||||
def attn1_proc(q, k, v, transformer_options):
|
||||
cond_indices = transformer_options['cond_indices']
|
||||
uncond_indices = transformer_options['uncond_indices']
|
||||
cond_or_uncond = transformer_options['cond_or_uncond']
|
||||
results = []
|
||||
|
||||
for cx in cond_or_uncond:
|
||||
if cx == 0:
|
||||
indices = cond_indices
|
||||
else:
|
||||
indices = uncond_indices
|
||||
|
||||
if len(indices) > 0:
|
||||
bq, bk, bv = q[indices], k[indices], v[indices]
|
||||
bo = aligned_attention(bq, bk, bv, transformer_options)
|
||||
results.append(bo)
|
||||
|
||||
results = torch.cat(results, dim=0)
|
||||
return results
|
||||
|
||||
unet.set_model_replace_all(attn1_proc, 'attn1')
|
||||
|
||||
p.sd_model.forge_objects.unet = unet
|
||||
|
||||
@@ -7,6 +7,7 @@ import modules.infotext_utils as parameters_copypaste
|
||||
from modules import script_callbacks
|
||||
from modules.paths import models_path
|
||||
from modules.ui_common import ToolButton, refresh_symbol
|
||||
from modules.ui_components import ResizeHandleRow
|
||||
from modules import shared
|
||||
|
||||
from modules_forge.forge_util import numpy_to_pytorch, pytorch_to_numpy, write_images_to_mp4
|
||||
@@ -59,7 +60,7 @@ def predict(filename, width, height, video_frames, motion_bucket_id, fps, augmen
|
||||
|
||||
def on_ui_tabs():
|
||||
with gr.Blocks() as svd_block:
|
||||
with gr.Row():
|
||||
with ResizeHandleRow():
|
||||
with gr.Column():
|
||||
input_image = gr.Image(label='Input Image', source='upload', type='numpy', height=400)
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import pathlib
|
||||
from modules import script_callbacks
|
||||
from modules.paths import models_path
|
||||
from modules.ui_common import ToolButton, refresh_symbol
|
||||
from modules.ui_components import ResizeHandleRow
|
||||
from modules import shared
|
||||
|
||||
from modules_forge.forge_util import numpy_to_pytorch, pytorch_to_numpy
|
||||
@@ -52,7 +53,7 @@ def predict(filename, width, height, batch_size, elevation, azimuth,
|
||||
|
||||
def on_ui_tabs():
|
||||
with gr.Blocks() as model_block:
|
||||
with gr.Row():
|
||||
with ResizeHandleRow():
|
||||
with gr.Column():
|
||||
input_image = gr.Image(label='Input Image', source='upload', type='numpy', height=400)
|
||||
|
||||
|
||||
@@ -2,8 +2,11 @@
|
||||
function extensions_apply(_disabled_list, _update_list, disable_all) {
|
||||
var disable = [];
|
||||
var update = [];
|
||||
|
||||
gradioApp().querySelectorAll('#extensions input[type="checkbox"]').forEach(function(x) {
|
||||
const extensions_input = gradioApp().querySelectorAll('#extensions input[type="checkbox"]');
|
||||
if (extensions_input.length == 0) {
|
||||
throw Error("Extensions page not yet loaded.");
|
||||
}
|
||||
extensions_input.forEach(function(x) {
|
||||
if (x.name.startsWith("enable_") && !x.checked) {
|
||||
disable.push(x.name.substring(7));
|
||||
}
|
||||
|
||||
@@ -114,6 +114,10 @@ function setupExtraNetworksForTab(tabname) {
|
||||
|
||||
var controls = gradioApp().querySelector("#" + tabname_full + "_controls");
|
||||
controlsDiv.insertBefore(controls, null);
|
||||
|
||||
if (elem.style.display != "none") {
|
||||
extraNetworksShowControlsForPage(tabname, tabname_full);
|
||||
}
|
||||
});
|
||||
|
||||
registerPrompt(tabname, tabname + "_prompt");
|
||||
@@ -168,7 +172,11 @@ function extraNetworksTabSelected(tabname, id, showPrompt, showNegativePrompt, t
|
||||
|
||||
function applyExtraNetworkFilter(tabname_full) {
|
||||
var doFilter = function() {
|
||||
extraNetworksApplyFilter[tabname_full](true);
|
||||
var applyFunction = extraNetworksApplyFilter[tabname_full];
|
||||
|
||||
if (applyFunction) {
|
||||
applyFunction(true);
|
||||
}
|
||||
};
|
||||
setTimeout(doFilter, 1);
|
||||
}
|
||||
@@ -622,10 +630,13 @@ function scheduleAfterScriptsCallbacks() {
|
||||
}, 200);
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", function() {
|
||||
onUiLoaded(function() {
|
||||
var mutationObserver = new MutationObserver(function(m) {
|
||||
if (!executedAfterScripts &&
|
||||
gradioApp().querySelectorAll("[id$='_extra_search']").length == 8) {
|
||||
let existingSearchfields = gradioApp().querySelectorAll("[id$='_extra_search']").length;
|
||||
let neededSearchfields = gradioApp().querySelectorAll("[id$='_extra_tabs'] > .tab-nav > button").length - 2;
|
||||
|
||||
if (!executedAfterScripts && existingSearchfields >= neededSearchfields) {
|
||||
mutationObserver.disconnect();
|
||||
executedAfterScripts = true;
|
||||
scheduleAfterScriptsCallbacks();
|
||||
}
|
||||
|
||||
@@ -45,8 +45,15 @@ function formatTime(secs) {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
var originalAppTitle = undefined;
|
||||
|
||||
onUiLoaded(function() {
|
||||
originalAppTitle = document.title;
|
||||
});
|
||||
|
||||
function setTitle(progress) {
|
||||
var title = 'Stable Diffusion';
|
||||
var title = originalAppTitle;
|
||||
|
||||
if (opts.show_progress_in_title && progress) {
|
||||
title = '[' + progress.trim() + '] ' + title;
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
(function() {
|
||||
const GRADIO_MIN_WIDTH = 320;
|
||||
const GRID_TEMPLATE_COLUMNS = '1fr 16px 1fr';
|
||||
const PAD = 16;
|
||||
const DEBOUNCE_TIME = 100;
|
||||
|
||||
@@ -23,21 +22,17 @@
|
||||
function displayResizeHandle(parent) {
|
||||
if (window.innerWidth < GRADIO_MIN_WIDTH * 2 + PAD * 4) {
|
||||
parent.style.display = 'flex';
|
||||
if (R.handle != null) {
|
||||
R.handle.style.opacity = '0';
|
||||
}
|
||||
parent.resizeHandle.style.display = "none";
|
||||
return false;
|
||||
} else {
|
||||
parent.style.display = 'grid';
|
||||
if (R.handle != null) {
|
||||
R.handle.style.opacity = '100';
|
||||
}
|
||||
parent.resizeHandle.style.display = "block";
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
function afterResize(parent) {
|
||||
if (displayResizeHandle(parent) && parent.style.gridTemplateColumns != GRID_TEMPLATE_COLUMNS) {
|
||||
if (displayResizeHandle(parent) && parent.style.gridTemplateColumns != parent.style.originalGridTemplateColumns) {
|
||||
const oldParentWidth = R.parentWidth;
|
||||
const newParentWidth = parent.offsetWidth;
|
||||
const widthL = parseInt(parent.style.gridTemplateColumns.split(' ')[0]);
|
||||
@@ -59,63 +54,94 @@
|
||||
|
||||
parent.style.display = 'grid';
|
||||
parent.style.gap = '0';
|
||||
parent.style.gridTemplateColumns = GRID_TEMPLATE_COLUMNS;
|
||||
const gridTemplateColumns = `${parent.children[0].style.flexGrow}fr ${PAD}px ${parent.children[1].style.flexGrow}fr`;
|
||||
parent.style.gridTemplateColumns = gridTemplateColumns;
|
||||
parent.style.originalGridTemplateColumns = gridTemplateColumns;
|
||||
|
||||
const resizeHandle = document.createElement('div');
|
||||
resizeHandle.classList.add('resize-handle');
|
||||
parent.insertBefore(resizeHandle, rightCol);
|
||||
parent.resizeHandle = resizeHandle;
|
||||
|
||||
resizeHandle.addEventListener('mousedown', (evt) => {
|
||||
if (evt.button !== 0) return;
|
||||
['mousedown', 'touchstart'].forEach((eventType) => {
|
||||
resizeHandle.addEventListener(eventType, (evt) => {
|
||||
if (eventType.startsWith('mouse')) {
|
||||
if (evt.button !== 0) return;
|
||||
} else {
|
||||
if (evt.changedTouches.length !== 1) return;
|
||||
}
|
||||
|
||||
evt.preventDefault();
|
||||
evt.stopPropagation();
|
||||
evt.preventDefault();
|
||||
evt.stopPropagation();
|
||||
|
||||
document.body.classList.add('resizing');
|
||||
document.body.classList.add('resizing');
|
||||
|
||||
R.tracking = true;
|
||||
R.parent = parent;
|
||||
R.parentWidth = parent.offsetWidth;
|
||||
R.handle = resizeHandle;
|
||||
R.leftCol = leftCol;
|
||||
R.leftColStartWidth = leftCol.offsetWidth;
|
||||
R.screenX = evt.screenX;
|
||||
R.tracking = true;
|
||||
R.parent = parent;
|
||||
R.parentWidth = parent.offsetWidth;
|
||||
R.leftCol = leftCol;
|
||||
R.leftColStartWidth = leftCol.offsetWidth;
|
||||
if (eventType.startsWith('mouse')) {
|
||||
R.screenX = evt.screenX;
|
||||
} else {
|
||||
R.screenX = evt.changedTouches[0].screenX;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
resizeHandle.addEventListener('dblclick', (evt) => {
|
||||
evt.preventDefault();
|
||||
evt.stopPropagation();
|
||||
|
||||
parent.style.gridTemplateColumns = GRID_TEMPLATE_COLUMNS;
|
||||
parent.style.gridTemplateColumns = parent.style.originalGridTemplateColumns;
|
||||
});
|
||||
|
||||
afterResize(parent);
|
||||
}
|
||||
|
||||
window.addEventListener('mousemove', (evt) => {
|
||||
if (evt.button !== 0) return;
|
||||
['mousemove', 'touchmove'].forEach((eventType) => {
|
||||
window.addEventListener(eventType, (evt) => {
|
||||
if (eventType.startsWith('mouse')) {
|
||||
if (evt.button !== 0) return;
|
||||
} else {
|
||||
if (evt.changedTouches.length !== 1) return;
|
||||
}
|
||||
|
||||
if (R.tracking) {
|
||||
evt.preventDefault();
|
||||
evt.stopPropagation();
|
||||
if (R.tracking) {
|
||||
if (eventType.startsWith('mouse')) {
|
||||
evt.preventDefault();
|
||||
}
|
||||
evt.stopPropagation();
|
||||
|
||||
const delta = R.screenX - evt.screenX;
|
||||
const leftColWidth = Math.max(Math.min(R.leftColStartWidth - delta, R.parent.offsetWidth - GRADIO_MIN_WIDTH - PAD), GRADIO_MIN_WIDTH);
|
||||
setLeftColGridTemplate(R.parent, leftColWidth);
|
||||
}
|
||||
let delta = 0;
|
||||
if (eventType.startsWith('mouse')) {
|
||||
delta = R.screenX - evt.screenX;
|
||||
} else {
|
||||
delta = R.screenX - evt.changedTouches[0].screenX;
|
||||
}
|
||||
const leftColWidth = Math.max(Math.min(R.leftColStartWidth - delta, R.parent.offsetWidth - GRADIO_MIN_WIDTH - PAD), GRADIO_MIN_WIDTH);
|
||||
setLeftColGridTemplate(R.parent, leftColWidth);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
window.addEventListener('mouseup', (evt) => {
|
||||
if (evt.button !== 0) return;
|
||||
['mouseup', 'touchend'].forEach((eventType) => {
|
||||
window.addEventListener(eventType, (evt) => {
|
||||
if (eventType.startsWith('mouse')) {
|
||||
if (evt.button !== 0) return;
|
||||
} else {
|
||||
if (evt.changedTouches.length !== 1) return;
|
||||
}
|
||||
|
||||
if (R.tracking) {
|
||||
evt.preventDefault();
|
||||
evt.stopPropagation();
|
||||
if (R.tracking) {
|
||||
evt.preventDefault();
|
||||
evt.stopPropagation();
|
||||
|
||||
R.tracking = false;
|
||||
R.tracking = false;
|
||||
|
||||
document.body.classList.remove('resizing');
|
||||
}
|
||||
document.body.classList.remove('resizing');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
|
||||
@@ -55,8 +55,8 @@ onOptionsChanged(function() {
|
||||
});
|
||||
|
||||
opts._categories.forEach(function(x) {
|
||||
var section = x[0];
|
||||
var category = x[1];
|
||||
var section = localization[x[0]] ?? x[0];
|
||||
var category = localization[x[1]] ?? x[1];
|
||||
|
||||
var span = document.createElement('SPAN');
|
||||
span.textContent = category;
|
||||
|
||||
@@ -48,11 +48,6 @@ function setupTokenCounting(id, id_counter, id_button) {
|
||||
var counter = gradioApp().getElementById(id_counter);
|
||||
var textarea = gradioApp().querySelector(`#${id} > label > textarea`);
|
||||
|
||||
if (opts.disable_token_counters) {
|
||||
counter.style.display = "none";
|
||||
return;
|
||||
}
|
||||
|
||||
if (counter.parentElement == prompt.parentElement) {
|
||||
return;
|
||||
}
|
||||
@@ -61,15 +56,32 @@ function setupTokenCounting(id, id_counter, id_button) {
|
||||
prompt.parentElement.style.position = "relative";
|
||||
|
||||
var func = onEdit(id, textarea, 800, function() {
|
||||
gradioApp().getElementById(id_button)?.click();
|
||||
if (counter.classList.contains("token-counter-visible")) {
|
||||
gradioApp().getElementById(id_button)?.click();
|
||||
}
|
||||
});
|
||||
promptTokenCountUpdateFunctions[id] = func;
|
||||
promptTokenCountUpdateFunctions[id_button] = func;
|
||||
}
|
||||
|
||||
function setupTokenCounters() {
|
||||
setupTokenCounting('txt2img_prompt', 'txt2img_token_counter', 'txt2img_token_button');
|
||||
setupTokenCounting('txt2img_neg_prompt', 'txt2img_negative_token_counter', 'txt2img_negative_token_button');
|
||||
setupTokenCounting('img2img_prompt', 'img2img_token_counter', 'img2img_token_button');
|
||||
setupTokenCounting('img2img_neg_prompt', 'img2img_negative_token_counter', 'img2img_negative_token_button');
|
||||
function toggleTokenCountingVisibility(id, id_counter, id_button) {
|
||||
var counter = gradioApp().getElementById(id_counter);
|
||||
|
||||
counter.style.display = opts.disable_token_counters ? "none" : "block";
|
||||
counter.classList.toggle("token-counter-visible", !opts.disable_token_counters);
|
||||
}
|
||||
|
||||
function runCodeForTokenCounters(fun) {
|
||||
fun('txt2img_prompt', 'txt2img_token_counter', 'txt2img_token_button');
|
||||
fun('txt2img_neg_prompt', 'txt2img_negative_token_counter', 'txt2img_negative_token_button');
|
||||
fun('img2img_prompt', 'img2img_token_counter', 'img2img_token_button');
|
||||
fun('img2img_neg_prompt', 'img2img_negative_token_counter', 'img2img_negative_token_button');
|
||||
}
|
||||
|
||||
onUiLoaded(function() {
|
||||
runCodeForTokenCounters(setupTokenCounting);
|
||||
});
|
||||
|
||||
onOptionsChanged(function() {
|
||||
runCodeForTokenCounters(toggleTokenCountingVisibility);
|
||||
});
|
||||
|
||||
@@ -324,8 +324,6 @@ onAfterUiUpdate(function() {
|
||||
});
|
||||
|
||||
json_elem.parentElement.style.display = "none";
|
||||
|
||||
setupTokenCounters();
|
||||
});
|
||||
|
||||
onOptionsChanged(function() {
|
||||
|
||||
@@ -41,6 +41,9 @@ def main():
|
||||
if args.test_server:
|
||||
configure_for_tests()
|
||||
|
||||
if args.forge_ref_a1111_home:
|
||||
launch_utils.configure_forge_reference_checkout(args.forge_ref_a1111_home)
|
||||
|
||||
start()
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
# https://github.com/comfyanonymous/ComfyUI/blob/master/nodes.py
|
||||
# Taken from https://github.com/comfyanonymous/ComfyUI
|
||||
# This file is only for reference, and not used in the backend or runtime.
|
||||
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
# https://github.com/comfyanonymous/ComfyUI/blob/master/nodes.py
|
||||
# Taken from https://github.com/comfyanonymous/ComfyUI
|
||||
# This file is only for reference, and not used in the backend or runtime.
|
||||
|
||||
|
||||
#From https://github.com/kornia/kornia
|
||||
import math
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
# https://github.com/comfyanonymous/ComfyUI/blob/master/nodes.py
|
||||
# Taken from https://github.com/comfyanonymous/ComfyUI
|
||||
# This file is only for reference, and not used in the backend or runtime.
|
||||
|
||||
|
||||
import torch
|
||||
from ldm_patched.contrib.external import MAX_RESOLUTION
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
# https://github.com/comfyanonymous/ComfyUI/blob/master/nodes.py
|
||||
# Taken from https://github.com/comfyanonymous/ComfyUI
|
||||
# This file is only for reference, and not used in the backend or runtime.
|
||||
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
# https://github.com/comfyanonymous/ComfyUI/blob/master/nodes.py
|
||||
# Taken from https://github.com/comfyanonymous/ComfyUI
|
||||
# This file is only for reference, and not used in the backend or runtime.
|
||||
|
||||
|
||||
import ldm_patched.modules.samplers
|
||||
import ldm_patched.modules.sample
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
# https://github.com/comfyanonymous/ComfyUI/blob/master/nodes.py
|
||||
# Taken from https://github.com/comfyanonymous/ComfyUI
|
||||
# This file is only for reference, and not used in the backend or runtime.
|
||||
|
||||
|
||||
import ldm_patched.modules.utils
|
||||
import ldm_patched.utils.path_utils
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
# https://github.com/comfyanonymous/ComfyUI/blob/master/nodes.py
|
||||
# Taken from https://github.com/comfyanonymous/ComfyUI
|
||||
# This file is only for reference, and not used in the backend or runtime.
|
||||
|
||||
|
||||
import ldm_patched.contrib.external
|
||||
import ldm_patched.utils.path_utils
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
# https://github.com/comfyanonymous/ComfyUI/blob/master/nodes.py
|
||||
# Taken from https://github.com/comfyanonymous/ComfyUI
|
||||
# This file is only for reference, and not used in the backend or runtime.
|
||||
|
||||
|
||||
import ldm_patched.modules.utils
|
||||
import torch
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
# https://github.com/comfyanonymous/ComfyUI/blob/master/nodes.py
|
||||
# Taken from https://github.com/comfyanonymous/ComfyUI
|
||||
# This file is only for reference, and not used in the backend or runtime.
|
||||
|
||||
|
||||
import numpy as np
|
||||
import scipy.ndimage
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
# https://github.com/comfyanonymous/ComfyUI/blob/master/nodes.py
|
||||
# Taken from https://github.com/comfyanonymous/ComfyUI
|
||||
# This file is only for reference, and not used in the backend or runtime.
|
||||
|
||||
|
||||
import ldm_patched.utils.path_utils
|
||||
import ldm_patched.modules.sd
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
# https://github.com/comfyanonymous/ComfyUI/blob/master/nodes.py
|
||||
# Taken from https://github.com/comfyanonymous/ComfyUI
|
||||
# This file is only for reference, and not used in the backend or runtime.
|
||||
|
||||
|
||||
import torch
|
||||
import ldm_patched.modules.utils
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
# https://github.com/comfyanonymous/ComfyUI/blob/master/nodes.py
|
||||
# Taken from https://github.com/comfyanonymous/ComfyUI
|
||||
# This file is only for reference, and not used in the backend or runtime.
|
||||
|
||||
|
||||
import ldm_patched.modules.sd
|
||||
import ldm_patched.modules.utils
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
# https://github.com/comfyanonymous/ComfyUI/blob/master/nodes.py
|
||||
# Taken from https://github.com/comfyanonymous/ComfyUI
|
||||
# This file is only for reference, and not used in the backend or runtime.
|
||||
|
||||
|
||||
import torch
|
||||
import ldm_patched.modules.model_management
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
# https://github.com/comfyanonymous/ComfyUI/blob/master/nodes.py
|
||||
# Taken from https://github.com/comfyanonymous/ComfyUI
|
||||
# This file is only for reference, and not used in the backend or runtime.
|
||||
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
# https://github.com/comfyanonymous/ComfyUI/blob/master/nodes.py
|
||||
# Taken from https://github.com/comfyanonymous/ComfyUI
|
||||
# This file is only for reference, and not used in the backend or runtime.
|
||||
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
# https://github.com/comfyanonymous/ComfyUI/blob/master/nodes.py
|
||||
# Taken from https://github.com/comfyanonymous/ComfyUI
|
||||
# This file is only for reference, and not used in the backend or runtime.
|
||||
|
||||
|
||||
import torch
|
||||
import ldm_patched.contrib.external
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# https://github.com/comfyanonymous/ComfyUI/blob/master/nodes.py
|
||||
|
||||
#Taken from: https://github.com/dbolya/tomesd
|
||||
# 1st edit: https://github.com/dbolya/tomesd
|
||||
# 2nd edit: https://github.com/comfyanonymous/ComfyUI
|
||||
# 3rd edit: Forge official
|
||||
|
||||
import torch
|
||||
from typing import Tuple, Callable
|
||||
@@ -146,34 +146,19 @@ def get_functions(x, ratio, original_shape):
|
||||
return nothing, nothing
|
||||
|
||||
|
||||
|
||||
class TomePatchModel:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": { "model": ("MODEL",),
|
||||
"ratio": ("FLOAT", {"default": 0.3, "min": 0.0, "max": 1.0, "step": 0.01}),
|
||||
}}
|
||||
RETURN_TYPES = ("MODEL",)
|
||||
FUNCTION = "patch"
|
||||
|
||||
CATEGORY = "_for_testing"
|
||||
class TomePatcher:
|
||||
def __init__(self):
|
||||
self.u = None
|
||||
|
||||
def patch(self, model, ratio):
|
||||
self.u = None
|
||||
def tomesd_m(q, k, v, extra_options):
|
||||
#NOTE: In the reference code get_functions takes x (input of the transformer block) as the argument instead of q
|
||||
#however from my basic testing it seems that using q instead gives better results
|
||||
m, self.u = get_functions(q, ratio, extra_options["original_shape"])
|
||||
return m(q), k, v
|
||||
|
||||
def tomesd_u(n, extra_options):
|
||||
return self.u(n)
|
||||
|
||||
m = model.clone()
|
||||
m.set_model_attn1_patch(tomesd_m)
|
||||
m.set_model_attn1_output_patch(tomesd_u)
|
||||
return (m, )
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"TomePatchModel": TomePatchModel,
|
||||
}
|
||||
return m
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
# https://github.com/comfyanonymous/ComfyUI/blob/master/nodes.py
|
||||
# Taken from https://github.com/comfyanonymous/ComfyUI
|
||||
# This file is only for reference, and not used in the backend or runtime.
|
||||
|
||||
|
||||
import os
|
||||
from ldm_patched.pfn import model_loading
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
# https://github.com/comfyanonymous/ComfyUI/blob/master/nodes.py
|
||||
# Taken from https://github.com/comfyanonymous/ComfyUI
|
||||
# This file is only for reference, and not used in the backend or runtime.
|
||||
|
||||
|
||||
import ldm_patched.contrib.external
|
||||
import torch
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
# Taken from https://github.com/comfyanonymous/ComfyUI
|
||||
# This file is only for reference, and not used in the backend or runtime.
|
||||
|
||||
|
||||
import math
|
||||
|
||||
from scipy import integrate
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
# Taken from https://github.com/comfyanonymous/ComfyUI
|
||||
# This file is only for reference, and not used in the backend or runtime.
|
||||
|
||||
|
||||
from contextlib import contextmanager
|
||||
import hashlib
|
||||
import math
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
# 1st edit by https://github.com/CompVis/latent-diffusion
|
||||
# 2nd edit by https://github.com/Stability-AI/stablediffusion
|
||||
# 3rd edit by https://github.com/Stability-AI/generative-models
|
||||
# 4th edit by https://github.com/comfyanonymous/ComfyUI
|
||||
# 5th edit by Forge
|
||||
|
||||
|
||||
import torch
|
||||
# import pytorch_lightning as pl
|
||||
import torch.nn.functional as F
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
# 1st edit by https://github.com/CompVis/latent-diffusion
|
||||
# 2nd edit by https://github.com/Stability-AI/stablediffusion
|
||||
# 3rd edit by https://github.com/Stability-AI/generative-models
|
||||
# 4th edit by https://github.com/comfyanonymous/ComfyUI
|
||||
# 5th edit by Forge
|
||||
|
||||
|
||||
import math
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
@@ -378,7 +385,7 @@ class CrossAttention(nn.Module):
|
||||
|
||||
self.to_out = nn.Sequential(operations.Linear(inner_dim, query_dim, dtype=dtype, device=device), nn.Dropout(dropout))
|
||||
|
||||
def forward(self, x, context=None, value=None, mask=None):
|
||||
def forward(self, x, context=None, value=None, mask=None, transformer_options=None):
|
||||
q = self.to_q(x)
|
||||
context = default(context, x)
|
||||
k = self.to_k(context)
|
||||
@@ -497,7 +504,7 @@ class BasicTransformerBlock(nn.Module):
|
||||
n = attn1_replace_patch[block_attn1](n, context_attn1, value_attn1, extra_options)
|
||||
n = self.attn1.to_out(n)
|
||||
else:
|
||||
n = self.attn1(n, context=context_attn1, value=value_attn1)
|
||||
n = self.attn1(n, context=context_attn1, value=value_attn1, transformer_options=extra_options)
|
||||
|
||||
if "attn1_output_patch" in transformer_patches:
|
||||
patch = transformer_patches["attn1_output_patch"]
|
||||
@@ -537,7 +544,7 @@ class BasicTransformerBlock(nn.Module):
|
||||
n = attn2_replace_patch[block_attn2](n, context_attn2, value_attn2, extra_options)
|
||||
n = self.attn2.to_out(n)
|
||||
else:
|
||||
n = self.attn2(n, context=context_attn2, value=value_attn2)
|
||||
n = self.attn2(n, context=context_attn2, value=value_attn2, transformer_options=extra_options)
|
||||
|
||||
if "attn2_output_patch" in transformer_patches:
|
||||
patch = transformer_patches["attn2_output_patch"]
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
# 1st edit by https://github.com/CompVis/latent-diffusion
|
||||
# 2nd edit by https://github.com/Stability-AI/stablediffusion
|
||||
# 3rd edit by https://github.com/Stability-AI/generative-models
|
||||
# 4th edit by https://github.com/comfyanonymous/ComfyUI
|
||||
# 5th edit by Forge
|
||||
|
||||
|
||||
# pytorch_diffusion + derived encoder decoder
|
||||
import math
|
||||
import torch
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
# 1st edit by https://github.com/CompVis/latent-diffusion
|
||||
# 2nd edit by https://github.com/Stability-AI/stablediffusion
|
||||
# 3rd edit by https://github.com/Stability-AI/generative-models
|
||||
# 4th edit by https://github.com/comfyanonymous/ComfyUI
|
||||
# 5th edit by Forge
|
||||
|
||||
|
||||
from abc import abstractmethod
|
||||
|
||||
import torch as th
|
||||
|
||||
@@ -1,3 +1,11 @@
|
||||
# 1st edit by https://github.com/CompVis/latent-diffusion
|
||||
# 2nd edit by https://github.com/Stability-AI/stablediffusion
|
||||
# 3rd edit by https://github.com/Stability-AI/generative-models
|
||||
# 4th edit by https://github.com/comfyanonymous/ComfyUI
|
||||
|
||||
# This file is only for reference, and not used in the backend or runtime.
|
||||
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import numpy as np
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
# 1st edit by https://github.com/CompVis/latent-diffusion
|
||||
# 2nd edit by https://github.com/Stability-AI/stablediffusion
|
||||
# 3rd edit by https://github.com/Stability-AI/generative-models
|
||||
|
||||
|
||||
# adopted from
|
||||
# https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py
|
||||
# and
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
# 1st edit by https://github.com/CompVis/latent-diffusion
|
||||
# 2nd edit by https://github.com/Stability-AI/stablediffusion
|
||||
|
||||
|
||||
import torch
|
||||
import numpy as np
|
||||
|
||||
|
||||
@@ -1,3 +1,12 @@
|
||||
# 1st edit by https://github.com/CompVis/latent-diffusion
|
||||
# 2nd edit by https://github.com/Stability-AI/stablediffusion
|
||||
# 3rd edit by https://github.com/Stability-AI/generative-models
|
||||
# 4th edit by https://github.com/comfyanonymous/ComfyUI
|
||||
|
||||
|
||||
# This file is not used in image diffusion backend.
|
||||
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
# Taken from https://github.com/comfyanonymous/ComfyUI
|
||||
# This file is only for reference, and not used in the backend or runtime.
|
||||
|
||||
|
||||
from ..diffusionmodules.upscaling import ImageConcatWithNoiseAugmentation
|
||||
from ..diffusionmodules.openaimodel import Timestep
|
||||
import torch
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
# 1st edit by https://github.com/Stability-AI/generative-models
|
||||
# 2nd edit by https://github.com/comfyanonymous/ComfyUI
|
||||
# 3rd edit by Forge
|
||||
|
||||
# This file is not used in image diffusion backend. (but used in SVD.)
|
||||
|
||||
|
||||
import functools
|
||||
from typing import Callable, Iterable, Union
|
||||
|
||||
|
||||