278 Commits

Author SHA1 Message Date
layerdiffusion
bfee03d8d9 pydantic 2024-06-27 00:28:53 -07:00
lllyasviel
0af28699c4 Update README.md (#802) 2024-06-08 11:28:32 -07:00
lllyasviel
29be1da7cf pass options to cross attention class 2024-03-08 00:50:29 -08:00
lllyasviel
10b5ca2541 vae already sliced in inner loop 2024-03-08 00:40:33 -08:00
lllyasviel
e48533bdcd change patcher method 2024-03-07 00:26:17 -08:00
Chengsong Zhang
b9705c58f6 fix alphas cumprod (#478)
* fix alphas cumprod

* indentation
2024-03-04 01:03:32 -06:00
lllyasviel
ce273aef88 Merge pull request #477 from lllyasviel/revert-475-conrevo/fix-alphas-cumprod
Revert "Fix alphas cumprod"
2024-03-03 22:41:15 -08:00
lllyasviel
95bcea72b1 Revert "fix alphas cumprod (#475)"
This reverts commit 72139b000c.
2024-03-03 22:40:56 -08:00
Chengsong Zhang
72139b000c fix alphas cumprod (#475) 2024-03-03 20:09:04 -06:00
lllyasviel
ef35383b4a VAE patcher and more types of unet patches 2024-02-29 22:37:34 -08:00
lllyasviel
b59deaa382 sync upstream 2024-02-26 10:34:28 -08:00
Andray
d23c694a84 fix resize handle 2024-02-26 07:00:08 -08:00
Andray
e9e8047978 register_tmp_file also with mtime 2024-02-26 07:00:08 -08:00
Andray
cc1c0829d5 fix resize-handle for vertical layout 2024-02-26 07:00:08 -08:00
AUTOMATIC1111
c8a5322d1f Merge pull request #15012 from light-and-ray/register_tmp_file-also-with-mtime
register_tmp_file also for mtime
2024-02-26 12:53:21 +03:00
AUTOMATIC1111
ca0308b60d Merge pull request #15010 from light-and-ray/fix_resize-handle_for_vertical_layout
Fix resize-handle visability for vertical layout (mobile)
2024-02-26 12:52:34 +03:00
Andray
6e6cc2922d fix resize handle 2024-02-26 13:37:29 +04:00
lllyasviel
5166a723c2 bring back tiling
close #215
2024-02-25 21:29:35 -08:00
lllyasviel
7155b993ca upstream sync 2024-02-25 20:51:52 -08:00
lllyasviel
1546fa8b89 upstream sync 2024-02-25 20:49:04 -08:00
lllyasviel
6287c73d98 rework memory management for extras
now face post-processing uses gpu
close #312
2024-02-25 20:37:14 -08:00
AUTOMATIC1111
2b7ddcbb5c Merge pull request #15006 from imnodb/master
fix: the `split_threshold` parameter does not work when running Split oversized images
2024-02-26 07:16:42 +03:00
AUTOMATIC1111
e3a8dc6e23 Merge pull request #15004 from light-and-ray/ResizeHandleRow_-_allow_overriden_column_scale_parametr
ResizeHandleRow - allow overriden column scale parametr
2024-02-26 07:16:24 +03:00
AUTOMATIC1111
ca8dc2bde2 Merge pull request #14995 from dtlnor/14591-bug-the-categories-layout-is-different-when-localization-is-on
Fix #14591 using translated content to do categories mapping
2024-02-26 07:12:31 +03:00
AUTOMATIC1111
900419e85e Merge pull request #14973 from AUTOMATIC1111/Fix-new-oft-boft
Fix the OFT/BOFT bugs when using new LyCORIS implementation
2024-02-26 07:12:12 +03:00
lllyasviel
a252bbcf16 change show_progress_type
will add Full back later after solving overhead problems
2024-02-25 19:55:56 -08:00
catboxanon
b458e42096 Fix LoRA infotext (#406) 2024-02-25 19:41:42 -08:00
catboxanon
beb6e76135 Fix version hyperlink (#407) 2024-02-25 19:41:11 -08:00
lllyasviel
056d4d0f91 fix for neveroom extension 2024-02-25 16:47:02 -08:00
lllyasviel
a0c89fae12 fix ci 2024-02-25 11:24:56 -08:00
lllyasviel
5e5b60b5b1 rework lora loading
and add logs
2024-02-25 11:04:14 -08:00
lllyasviel
437c348926 Add build-in extension "NeverOOM"
see also discussions
2024-02-24 19:09:06 -08:00
lllyasviel
50229a05c1 revise doc 2024-02-24 14:49:29 -08:00
lllyasviel
434ca2169f Add optimization --cuda-stream
See also the readme for more details
2024-02-24 14:00:48 -08:00
lllyasviel
0f09d98814 revise memory formulation for special amd like #343 2024-02-24 09:36:52 -08:00
lllyasviel
79bdb78619 less verbose 2024-02-23 22:31:16 -08:00
lllyasviel
2ecb869f31 try solve #386 2024-02-23 20:43:06 -08:00
lllyasviel
a844834193 safer stream initialization 2024-02-23 20:28:27 -08:00
lllyasviel
d508d8132f add cmd flag hints 2024-02-23 20:06:08 -08:00
lllyasviel
88f395091b add two optimizations
--pin-shared-memory and --cuda-malloc

See also the updates in Readme for more details
2024-02-23 18:39:32 -08:00
lllyasviel
54c89503eb Disable pin page
This is an emergency fix

GTX 1060/1050/1066 either does not have shared GPU page vram or have less than 2GB shared page vram - pinning any tensors larger than that will crash

Solution is still under investigation.
2024-02-23 16:43:08 -08:00
lllyasviel
16caff3d14 Revert "try solve #381"
This reverts commit 9d4c88912d.
2024-02-23 16:13:40 -08:00
lllyasviel
9d4c88912d try solve #381
caused by some potential historical webui problems
2024-02-23 16:01:40 -08:00
lllyasviel
bde779a526 apply_token_merging 2024-02-23 15:43:27 -08:00
lllyasviel
2a7fb1be24 less verbose 2024-02-23 14:22:37 -08:00
lllyasviel
cc5f773519 sync upstream 2024-02-23 13:48:28 -08:00
lllyasviel
1c6e4b698b Merge branch 'dev' of github.com:AUTOMATIC1111/stable-diffusion-webui into dev 2024-02-23 13:45:46 -08:00
lllyasviel
ad0ce480f9 always print time 2024-02-23 13:02:30 -08:00
lllyasviel
df12dde12e Rework unload system
Previous repeated loading (on cn or other extensions) is fixed. ControlNet saves about 0.7 to 1.1 seconds on my two device when batch count > 1. 

8GB VRAM can use SDXL at resolution 6144x6144 now, out of the box, without tiled diffusion or other things. 

(the max resolution on Automatic1111 txt2img UI is 2048 but one can highres fix to try 6144 or even 8192)
2024-02-23 12:58:09 -08:00
lllyasviel
19473b1a26 fix ci 2024-02-23 09:44:08 -08:00
lllyasviel
26c325296e rework memory computation for async loader (#377) 2024-02-23 09:24:39 -08:00
Andray
3a99824638 register_tmp_file also with mtime 2024-02-23 20:26:56 +04:00
Andray
bab918f049 fix resize-handle for vertical layout 2024-02-23 18:34:24 +04:00
DB Eriospermum
ed594d7ba6 fix: the split_threshold parameter does not work when running Split oversized images 2024-02-23 13:37:37 +08:00
lllyasviel
eacb14e115 tune threshold based on more test devices
for async mover
2024-02-22 17:18:31 -08:00
Andray
9211febbfc ResizeHandleRow - allow overriden column scale parametr 2024-02-23 02:32:12 +04:00
AUTOMATIC1111
18819723c1 Merge pull request #15002 from light-and-ray/support_resizable_columns_for_touch_(tablets)
support resizable columns for touch (tablets)
2024-02-22 22:59:26 +03:00
AUTOMATIC1111
3f18a09c86 make extra network card description plaintext by default, with an option to re-enable HTML as it was 2024-02-22 21:27:10 +03:00
lllyasviel
8283774b86 revise caster 2024-02-22 10:24:27 -08:00
lllyasviel
6ebef20db3 avoid potential OOM caused by computation being slower than mover
avoid OOM (or shared vram invoking) caused by computation being slower than mover (GPU filled with loaded  but uncomputed tensors), by setting the max async overhead to 512MB
2024-02-22 08:24:23 -08:00
lllyasviel
167dbc6411 safe value for new memory peak 2024-02-22 06:31:21 -08:00
Andray
58985e6b37 fix lint 2 2024-02-22 17:22:00 +04:00
Andray
ab1e0fa9bf fix lint and console warning 2024-02-22 17:16:16 +04:00
Andray
85abbbb8fa support resizable columns for touch (tablets) 2024-02-22 17:04:56 +04:00
lllyasviel
539bc5035d safe cleanup to avoid potential problems 2024-02-22 01:28:38 -08:00
lllyasviel
4080e25805 add todo note 2024-02-22 00:47:26 -08:00
lllyasviel
846fdc3341 also implement async offload to control-lora
controlnet, t2iadapters, etc
2024-02-22 00:20:35 -08:00
lllyasviel
638ee43bf1 Merge upstream PR 14855 2024-02-21 23:59:40 -08:00
lllyasviel
95ddac3117 Merge upstream
upstream
2024-02-21 23:56:45 -08:00
lllyasviel
b713542cd8 resolve upstream 2024-02-21 23:54:21 -08:00
lllyasviel
b4f3c1971b Merge branch 'dev' of github.com:AUTOMATIC1111/stable-diffusion-webui into dev 2024-02-21 23:44:47 -08:00
AUTOMATIC1111
1da05297ea possible fix for reload button not appearing in some cases for extra networks. 2024-02-22 10:28:03 +03:00
dtlnor
f537e5a519 fix #14591 - using translated content to do categories mapping 2024-02-22 12:26:57 +09:00
lllyasviel
4ce60f2176 support SDXL-Lightning
added samplers: Euler SGMUniform, Euler A SGMUniform, DPM++ 2M SGMUniform, DPM++ 2M SDE SGMUniform

ByteDance official recommended one is Euler SGMUniform

Remember to use CFG=1.0
2024-02-21 15:42:38 -08:00
Kohaku-Blueleaf
c4afdb7895 For no constraint 2024-02-22 00:43:32 +08:00
Kohaku-Blueleaf
64179c3221 Update network_oft.py 2024-02-21 22:50:43 +08:00
Kohaku-Blueleaf
591470d86d linting 2024-02-20 17:21:34 +08:00
Kohaku-Blueleaf
a5436a3ac0 Update network_oft.py 2024-02-20 17:20:14 +08:00
AUTOMATIC1111
0a271938d8 Merge pull request #14966 from light-and-ray/avoid_doble_upscaling_in_inpaint
[bug] avoid doble upscaling in inpaint
2024-02-19 18:06:05 +03:00
Andray
33c8fe1221 avoid doble upscaling in inpaint 2024-02-19 16:57:49 +04:00
AUTOMATIC1111
6e4fc5e1a8 Merge pull request #14871 from v0xie/boft
Support inference with LyCORIS BOFT networks
2024-02-19 10:05:30 +03:00
Kohaku-Blueleaf
4eb949625c prevent undefined variable 2024-02-19 14:43:07 +08:00
Kohaku-Blueleaf
5a8dd0c549 Fix rescale 2024-02-18 14:58:41 +08:00
AUTOMATIC1111
9d5becb4de Merge pull request #14947 from AUTOMATIC1111/open-button
option "open image button" open the actual dir
2024-02-17 21:30:21 +03:00
w-e-w
71072f5620 re-work open image button settings 2024-02-18 02:47:44 +09:00
lllyasviel
43c9e3b5ce begin to use double versioning
now you will see things like f0.0.14v1.8.0rc. It means forge 0.0.14 on webui 1.8.0rc
2024-02-17 08:32:15 -08:00
lllyasviel
ae51178629 allow extensions to sort themselves in UI
and other installed extensions will be on top now (including some resolution related UI extensions)
2024-02-17 08:15:29 -08:00
lllyasviel
07659efd88 fix import order 2024-02-17 08:03:17 -08:00
lllyasviel
9e42470a2d sync webui 1.8.0rc 2024-02-17 07:45:06 -08:00
lllyasviel
7a2aca6fed Merge branch 'main' into tdd 2024-02-17 07:40:16 -08:00
w-e-w
a18e54ecd7 option "open image button" open the actual dir 2024-02-18 00:38:05 +09:00
lllyasviel
7071321792 Merge branch 'dev' of github.com:AUTOMATIC1111/stable-diffusion-webui into dev 2024-02-17 07:36:43 -08:00
AUTOMATIC1111
4ff1fabc86 Update comment for Pad prompt/negative prompt v0 to add a warning about truncation, make it override the v1 implementation 2024-02-17 13:21:08 +03:00
AUTOMATIC1111
4573195894 prevent escape button causing an interrupt when no generation has been made yet 2024-02-17 11:40:53 +03:00
AUTOMATIC1111
db19c46d6d lint 2024-02-17 10:32:10 +03:00
AUTOMATIC1111
1466daeafc Disable prompt token counters option actually disables token counting rather than just hiding results.
Disable prompt token counters option does not require reload UI.
token counters do not become visible until they are positioned correctly.
2024-02-17 10:31:16 +03:00
AUTOMATIC1111
dd1641ecc4 fix an exception when filtering extra networks very early 2024-02-17 09:46:04 +03:00
AUTOMATIC1111
7dae6bb3b5 fix search UI invisible in an extra network tab that just loaded 2024-02-17 09:45:48 +03:00
AUTOMATIC1111
2e1b61e590 change condition for scheduleAfterScriptsCallbacks() to properly reflect the needed amount of search fields 2024-02-17 09:45:03 +03:00
AUTOMATIC1111
f293dbbf97 Merge pull request #14900 from AUTOMATIC1111/fix-css-color-extra-network-control--enabled
fix extra-network-control--enabled color
2024-02-17 09:00:06 +03:00
AUTOMATIC1111
bf08a5b75e Merge pull request #14910 from analysisjp/wsl2_flx
fixed webui.sh issue that occurred in WSL environment (fix: #14883)
2024-02-17 08:59:41 +03:00
AUTOMATIC1111
48ce0379bc Merge pull request #14916 from light-and-ray/use_original_document_title
Use original App Title in progress bar
2024-02-17 08:57:56 +03:00
AUTOMATIC1111
d235aa068d Merge pull request #14932 from AUTOMATIC1111/fix/esc-interrupt
Only trigger interrupt on `Esc` when interrupt button visible
2024-02-17 08:57:25 +03:00
AUTOMATIC1111
ce57a6c6db Merge pull request #14933 from AUTOMATIC1111/fix/graceful-mtime-hash-cache-exception
Gracefully handle mtime read exception from cache
2024-02-17 08:56:48 +03:00
AUTOMATIC1111
d70632a7cf Merge pull request #14934 from AUTOMATIC1111/fix/normalize-cmd-arg-paths
Normalize command-line argument paths
2024-02-17 08:54:06 +03:00
AUTOMATIC1111
4333ecc43f Merge pull request #14939 from AUTOMATIC1111/Fix-extranetworks-search-reload
Fix the bugs that search/reload will disappear when using other ExtraNetworks extensions
2024-02-17 08:51:11 +03:00
AUTOMATIC1111
a56125b0a8 Merge pull request #14930 from RedDeltas/feat/launch_utils/file_mode_for_clone
Added core.filemode=false so doesn't track changes in file permission…
2024-02-17 08:48:37 +03:00
Kohaku-Blueleaf
23f03d4796 Update extraNetworks.js 2024-02-16 16:43:43 +08:00
catboxanon
06ab10a1be Normalize cmd arg paths
In particular, this fixes an issue on Windows where some functions
will misbehave if forward slashes are provided rather than
double backslashes.
2024-02-15 14:22:13 -05:00
catboxanon
6ee4012c0a Gracefully handle mtime read exception from cache 2024-02-15 13:31:44 -05:00
catboxanon
46988af636 Fix Esc interrupt when button not visible 2024-02-15 13:05:39 -05:00
RedDeltas
18ec22bffe Added core.filemode=false so doesn't track changes in file permissions in more restrictive environments 2024-02-15 12:26:14 +00:00
Andray
1142201a3a Use original App Title in progress bar 2024-02-14 15:26:57 +04:00
lllyasviel
d81e353d89 fix outpaint in inpaint_only+lama
the problem in inpaint_only+lama+"Resize and Fill" is fixed now.
SDXL+inpaint_only+lama+"Resize and Fill"+inpaint_fooocus_v26+"stop at 0.5 or 0.6" can be used as one SOTA outpaint method now
2024-02-14 02:45:23 -08:00
lllyasviel
fa8be06613 fix tile-colorfix problems
This will completely solve problems related to tile-colorfix and now tile colorfix/colorfix+sharp give same results to webui-cn
2024-02-14 02:19:04 -08:00
lllyasviel
b50d978e1b reduce difference of tile-colorfix to webui cn 2024-02-13 20:45:11 -08:00
Yuki Shindo
2616c20687 fix embeddings path (#237) 2024-02-13 19:48:06 -05:00
analysisjp
69f9564a6d fixed webui.sh issue that occurred in WSL environment (fix: #14883) 2024-02-13 21:49:23 +09:00
Chenlei Hu
4777898a0c Update hand refiner (#219) 2024-02-12 21:59:44 -08:00
Kohaku-Blueleaf
90441294db Add rescale mechanism
LyCORIS will support save oft_blocks instead of oft_diag in the near future (for both OFT and BOFT)

But this means we need to store the rescale if user enable it.
2024-02-12 14:25:09 +08:00
lllyasviel
3cdae09639 try solve saturation problems for instant id in #155 2024-02-11 20:53:17 -08:00
lllyasviel
237f80681a add more notes to clip codes 2024-02-11 20:28:02 -08:00
lllyasviel
30dd8af08c fix error in head info 2024-02-11 20:12:27 -08:00
lllyasviel
3d039591fe Expand head info in files
Previously before this commit, credits are already in entry and licenses are already in root. This commit will make info clearer.
2024-02-11 19:55:18 -08:00
Chenlei Hu
9c5038c766 Add --forge-ref-a1111-home cmd arg to reference existing A1111 checkout (#203)
* Add --forge-ref-a1111-home cmd arg to reference existing A1111 checkout

* nit
2024-02-11 21:22:31 -05:00
Chengsong Zhang
f5bf7799f4 AnimateDiff Update in README (#204)
* animatediff update|

* readme
2024-02-11 19:13:41 -06:00
lllyasviel
11dcc6c96c solve lereas++ device #174 2024-02-11 16:53:19 -08:00
lllyasviel
bc5589b249 upstream dev commits 2024-02-11 16:45:07 -08:00
lllyasviel
30c8d742b3 Merge branch 'main' into upt 2024-02-11 16:42:36 -08:00
lllyasviel
eca4d296f5 Merge branch 'dev' of github.com:AUTOMATIC1111/stable-diffusion-webui into dev 2024-02-11 16:39:04 -08:00
w-e-w
13fd466c18 fix extra-network-control--enabled color
also add forgotten semicolon
2024-02-12 04:07:14 +09:00
Chenlei Hu
8316773caa Fix inpaint mask in API (#188)
* Fix inpaint mask in API

* Add more tests

* Add tests
2024-02-11 11:49:21 -05:00
AUTOMATIC1111
b7f45e67dc add before_token_counter callback and use it for prompt comments 2024-02-11 12:56:53 +03:00
AUTOMATIC1111
02ab75b86a Count tokens of enabled styles 2024-02-11 12:40:27 +03:00
AUTOMATIC1111
f6e476d7a8 call the right function for token counter in img2img 2024-02-11 12:24:02 +03:00
AUTOMATIC1111
b531b0bbef add propmpt comments support 2024-02-11 12:23:21 +03:00
AUTOMATIC1111
e2b19900ec add infotext entry for emphasis; put emphasis into a separate file, add an option to parse but still ignore emphasis 2024-02-11 09:39:51 +03:00
Chenlei Hu
e11753ff84 Fix controlnet/detect API endpoint (#187) 2024-02-11 01:15:06 -05:00
AUTOMATIC1111
3732cf2f97 Merge pull request #14874 from hako-mikan/master
Add option to disable normalize embeddings after after calculating emphasis.
2024-02-11 08:34:40 +03:00
AUTOMATIC1111
2f1e2c492f Merge pull request #14873 from AUTOMATIC1111/check_extensions_list_on_apply_js_method
if extensions page not loaded, prevent apply
2024-02-11 08:29:54 +03:00
AUTOMATIC1111
860534399b Merge pull request #14879 from AUTOMATIC1111/walk_files-extensions-case-insensitive
util.walk_files extensions case insensitive
2024-02-11 08:29:05 +03:00
AUTOMATIC1111
4d46f8c25c Merge pull request #14883 from analysisjp/dev_fix_memleak_new
fix prepare_tcmalloc (fix: #14227)(Fixed memory leak issue in Ubuntu 22.04 or modern linux environment)
2024-02-11 08:28:42 +03:00
AUTOMATIC1111
5ddd5d29e5 Merge pull request #14884 from light-and-ray/ResizeHandleRow_png_info_and_train
ResizeHandleRow png_info and train
2024-02-11 08:26:20 +03:00
AUTOMATIC1111
440fff64a2 Merge pull request #14890 from AUTOMATIC1111/always-append-timestamp
Always add timestamp to displayed image
2024-02-11 08:26:00 +03:00
AUTOMATIC1111
d2246df160 Merge pull request #14885 from AUTOMATIC1111/extensions-tab-table-row-hover-highlight
extensions tab table row hover highlight
2024-02-11 08:24:41 +03:00
Chenlei Hu
6a854fcb38 Add documentation on ControlNetUnit (#176)
* remove dict from any

* nit

* nit
2024-02-10 22:30:22 -05:00
lllyasviel
ee023f4fbf Fix UniPC data cast and shape broadcast in #184
Fix UniPC data cast and shape broadcast in #184

This also fix potential problems in DDIM. The cause of this BUG is A1111’s `modules\models\diffusion\uni_pc\uni_pc.py` does not have a data cast and the Forge’s DDIM estimator forget to match the broadcast shape of sigmas.

(At the same time when we are fixing this BUG in A1111’s very original and high-quality samplers, comfyanonymous is still believing that Forge is using comfyui to sample images, eg, ComfyUI UniPC.
Comfyanonymous is so cute.
See also the jokes here https://github.com/lllyasviel/stable-diffusion-webui-forge/discussions/169#discussioncomment-8428689)
2024-02-10 18:35:42 -08:00
missionfloyd
c04c4b95de Always add timestamp to displayed image 2024-02-10 14:49:08 -07:00
lllyasviel
15bb49e761 add backend note 2024-02-10 05:39:03 -08:00
lllyasviel
6e71d97478 Update forge_version.py 2024-02-10 03:25:27 -08:00
lllyasviel
998327c744 add edit model 2024-02-10 03:24:40 -08:00
w-e-w
7583351760 extensions tab table row hover highlight 2024-02-10 18:09:10 +09:00
Andray
82e2e25325 ResizeHandleRow png_info and train 2024-02-10 13:00:16 +04:00
Andray
44b647a83e Use ResizeHandleRow for z123 and svd (#168) 2024-02-10 00:57:12 -08:00
lllyasviel
ce21e7afe4 fix degradation 2024-02-09 23:09:01 -08:00
lllyasviel
ac94f38d9a Update forge_version.py 2024-02-09 22:21:53 -08:00
Chenlei Hu
5a7e755528 ControlNet API (#162)
* ControlNet API

* update cache key

* nits

* disable controlnet tests
2024-02-10 01:16:13 -05:00
lllyasviel
bd0878754c apply loras to refiner like upstream #161 2024-02-09 21:40:19 -08:00
lllyasviel
371687a1da fix degradation 2024-02-09 20:58:38 -08:00
lllyasviel
e9459b6c4a support sd1.5 model with v prediction #123 2024-02-09 20:51:18 -08:00
Chengsong Zhang
ee565b337c ControlNet batch fix (#113)
* cn forward patcher

* simplify

* use args instead of kwargs

* postpond moving cond_hint to gpu

* also do this for t2i adapter

* use a1111's code to load files in a batch

* revert

* patcher for batch images

* patcher for batch images

* remove cn fn wrapper dupl

* remove shit

* use unit getattr instead of unet patcher

* fix bug

* small changte
2024-02-09 21:55:29 -06:00
lllyasviel
d6f2e5bdd9 Disable Legacy Multidiffusion
Both Multidiffusion and Tiled VAE are integrated and this extension can be disabled
2024-02-09 19:07:50 -08:00
lllyasviel
dca0a1d5d8 Integrate Multi Diffusion
Integrated Multi Diffusion, based on codes from pkuliyi2015 and shiimizu
Basic Diffusion test passed
ControlNet test passed
2024-02-09 18:37:32 -08:00
lllyasviel
4ec1015162 fix mask can be none 2024-02-09 18:25:44 -08:00
analysisjp
2ba0277b52 fix: prepare_tcmalloc (Fixed memory leak issue in Ubuntu 22.04 or modern linux environment) 2024-02-10 10:09:19 +09:00
lllyasviel
fb2e271668 support inpaint models from fooocus
put inpaint_v26.fooocus.patch in models\ControlNet, control SDXL models only
To get same algorithm as Fooocus, set "Stop at" (Ending Control Step) to 0.5
Fooocus always use 0.5 but in Forge users may use other values.
Results are best when stop at < 0.7. The model is not optimized with ending timesteps > 0.7
Supports inpaint_global_harmonious, inpaint_only, inpaint_only+lama.
In theory the inpaint_only+lama always outperform Fooocus in object removal task (but not all tasks).
2024-02-09 17:08:48 -08:00
lllyasviel
d2af6d1b44 Contribution Guideline 2024-02-09 14:57:45 -08:00
lllyasviel
54edd29725 integrate latent modifier 2024-02-09 14:38:57 -08:00
lllyasviel
8c8f948666 integrated DynamicThresholding (CFG-Fix) 2024-02-09 14:11:59 -08:00
lllyasviel
8059533eaf fix lora not loaded for text encoder #142 2024-02-09 13:50:50 -08:00
Chenlei Hu
200f2b69ed Add back ControlNet model version filter (#131)
* Add back ControlNet model version filter

* Update choice after sd model changes
2024-02-09 16:34:09 -05:00
Chenlei Hu
ac4a8820a5 Fix CQ tests (#141)
* Make test client run on cpu

* test on cpu

try fix device

try fix device

try fix device

* Use real SD1.5 model for testing

* ckpt nits

* Remove coverage calls
2024-02-09 16:33:05 -05:00
lllyasviel
472a510151 try fix control mode weighting #155 2024-02-09 13:23:49 -08:00
Andray
e8f51579cc add button for refreshing extensions list 2024-02-09 13:12:14 -08:00
lllyasviel
658da35cdc Merge branch 'dev' of github.com:AUTOMATIC1111/stable-diffusion-webui into dev 2024-02-09 13:10:55 -08:00
w-e-w
542611cce4 walk_files extensions case insensitive 2024-02-10 05:39:01 +09:00
Chenlei Hu
c06769c1fa Temporarily disable CQ unittests (#154) 2024-02-09 12:11:11 -05:00
hako-mikan
c3c88ca8b4 Update sd_hijack_clip.py 2024-02-10 00:18:08 +09:00
hako-mikan
6b3f7039b6 add option 2024-02-09 23:57:46 +09:00
w-e-w
6b8458eb9f if extensions page not loaded, prevent apply
since they are built-in extensions we can make the assumption that they will be at least one or more extensions

Co-Authored-By: Andray <33491867+light-and-ray@users.noreply.github.com>
2024-02-09 23:19:39 +09:00
hako-mikan
0bc7867ccd Merge branch 'AUTOMATIC1111:master' into master 2024-02-09 23:17:40 +09:00
AUTOMATIC1111
d69a7944c9 Merge pull request #14857 from light-and-ray/refresh_extensions_list
Button for refresh extensions list
2024-02-09 16:06:02 +03:00
v0xie
eb6f2df826 Revert "fix: add butterfly_factor fn"
This reverts commit 81c16c965e.
2024-02-08 22:00:15 -08:00
v0xie
613b0d9548 doc: add boft comment 2024-02-08 21:58:59 -08:00
Chenlei Hu
ed60a99826 Fix import error (#146) 2024-02-08 23:02:33 -05:00
Chenlei Hu
61db0fba41 Ignore ruff directorys (#145) 2024-02-08 21:55:21 -05:00
Chenlei Hu
3c32cbb0af Revert "Fix more ruff lint (#139)" (#144)
This reverts commit e13072cb42.
2024-02-08 21:34:58 -05:00
Chenlei Hu
388ca351f4 Revert "Fix ruff linter (#137)" (#143)
This reverts commit 6b3ad64388.
2024-02-08 21:24:04 -05:00
Chenlei Hu
b49742354d Fix CQ server arg (#140) 2024-02-08 20:50:03 -05:00
Chenlei Hu
e13072cb42 Fix more ruff lint (#139) 2024-02-08 20:41:38 -05:00
Chenlei Hu
6b3ad64388 Fix ruff linter (#137)
* Fix ruff linter

* Remove unused imports

* Remove unused imports
2024-02-08 20:35:20 -05:00
Chenlei Hu
66c22490c3 Ignore ControlNet extension in eslint (#136) 2024-02-08 19:48:49 -05:00
Yuki Shindo
847d451505 Fix command line arguments format in webui-user.bat (#135)
* fix command line arguments format in webui-user.bat

* fix embeddings dir path
2024-02-08 19:47:42 -05:00
v0xie
325eaeb584 fix: get boft params from weight shape 2024-02-08 11:55:05 -08:00
lllyasviel
f06ba8e60b Significantly reduce thread abuse for faster model moving
This will move all major gradio calls into the main thread rather than random gradio threads.
This ensures that all torch.module.to() are performed in main thread to completely possible avoid GPU fragments.
In my test now model moving is 0.7 ~ 1.2 seconds faster, which means all 6GB/8GB VRAM users will get 0.7 ~ 1.2 seconds faster per image on SDXL.
2024-02-08 10:13:59 -08:00
lllyasviel
291ec743b6 use better context manager to fix potential problems 2024-02-08 02:00:54 -08:00
lllyasviel
760f727eb9 use better context manager to fix potential problems 2024-02-08 01:51:18 -08:00
lllyasviel
4c9db26541 support controlnet_model_function_wrapper for t2i-adapter 2024-02-07 21:42:56 -08:00
lllyasviel
50035ad414 fix outpaint with inpaint_global_harmonious 2024-02-07 20:31:22 -08:00
lllyasviel
49ec325f6a lin 2024-02-07 20:14:02 -08:00
lllyasviel
a1670c536d Allow controlnet_model_function_wrapper
for animatediff to manage controlnet batch slicing window
2024-02-07 20:06:23 -08:00
Chenlei Hu
383aaca1eb Improve model filtering (#114) 2024-02-07 22:53:41 -05:00
lllyasviel
42dd258c8d revise attention alignment in stylealign #100
A mistake in 0day release is that the attention layers of cond and uncond items in a batch are aligned when they should not.
after align batch in cond and uncond separately they now works and give same results to legacy sd-webui-cnet
2024-02-07 19:11:53 -08:00
lllyasviel
f63917a323 add codes discussed in #73 that may help ipadapters 2024-02-07 18:57:57 -08:00
lllyasviel
ef781cabcb Backend: Allow control signal to be none for advanced weighting 2024-02-07 13:02:42 -08:00
lllyasviel
c3a66b016b try solve dtype cast for #112 2024-02-07 12:39:55 -08:00
Chenlei Hu
e1faf8327b Add back ControlNet HR option (#90)
* Add back ControlNet HR option

* nits

* protect kernel

* add enum

* fix

* fix

* Update controlnet.py

* restore controlnet.py

* hint ui

* Update controlnet.py

* fix

* Update controlnet.py

* Backend: better controlnet mask batch broadcasting

* Update README.md

* fix inpaint batch dim align #94

* fix sigmas device in rare cases #71

* rework sigma device mapping

* Add hr_option to infotext

---------

Co-authored-by: lllyasviel <lyuminzhang@outlook.com>
2024-02-07 11:09:52 -05:00
v0xie
2f1073dc6e style: fix lint 2024-02-07 04:55:11 -08:00
v0xie
81c16c965e fix: add butterfly_factor fn 2024-02-07 04:54:14 -08:00
v0xie
a4668a16b6 fix: calculate butterfly factor 2024-02-07 04:51:22 -08:00
v0xie
9588721197 feat: support LyCORIS BOFT 2024-02-07 04:49:17 -08:00
Andray
99c6c4a51b add button for refreshing extensions list 2024-02-07 16:06:17 +04:00
lllyasviel
257ac2653a rework sigma device mapping 2024-02-07 00:44:12 -08:00
lllyasviel
d11c9d7506 fix sigmas device in rare cases #71 2024-02-06 23:12:35 -08:00
lllyasviel
4ea4a92fe9 fix inpaint batch dim align #94 2024-02-06 22:57:53 -08:00
lllyasviel
65f9c7d442 Update README.md 2024-02-06 21:46:54 -08:00
lllyasviel
c185e39e59 Backend: better controlnet mask batch broadcasting 2024-02-06 20:13:09 -08:00
Chenlei Hu
1110183943 Fix ControlNet UI preset (#87) 2024-02-06 21:52:04 -05:00
lllyasviel
e62631350a Update forge_version.py 2024-02-06 17:55:14 -08:00
lllyasviel
e579fab4d0 try solve #71 2024-02-06 17:46:23 -08:00
lllyasviel
6301a6660e solve #73 2024-02-06 17:28:00 -08:00
lllyasviel
711844ecd8 solve #76 2024-02-06 17:25:28 -08:00
lllyasviel
70ae2a4bce fix controlnet ignored in batch #55 2024-02-06 17:12:57 -08:00
lllyasviel
fc5c70a28d gradio fix 2024-02-06 14:32:42 -08:00
Chengsong Zhang
b58b0bd425 batch mask (#44)
* mask batch, not working

* mask batch, working, infotext broken

* try remove old codes

* set CUDA_VISIBLE_DEVICES with args

* Revert "try remove old codes"

This reverts commit 63c527c373.

* Update controlnet_ui_group.py

* readme

* 🐛 Fix infotext

---------

Co-authored-by: lllyasviel <lyuminzhang@outlook.com>
Co-authored-by: huchenlei <chenlei.hu@mail.utoronto.ca>
2024-02-06 12:54:35 -06:00
lllyasviel
5bea443d94 add a note after fixing repeated loading bug on 4090 2024-02-06 08:13:29 -08:00
Chenlei Hu
79e4e46061 🐛 Fix SVD tab (#63) 2024-02-06 11:10:47 -05:00
lllyasviel
402b7beb87 fix repeated model loading bug on 4090 2024-02-06 08:02:03 -08:00
lllyasviel
a578da074b fix repeated model loading bug on 4090 2024-02-06 07:59:19 -08:00
lllyasviel
d76b830add reduce prints 2024-02-06 07:56:15 -08:00
lllyasviel
65367aa24d accurate words 2024-02-06 07:51:37 -08:00
lllyasviel
4939cf18d8 update hints for 4090 2024-02-06 07:43:33 -08:00
lllyasviel
7359740f36 Revert "safer device"
This reverts commit 1204d490d9.
2024-02-06 05:27:07 -08:00
lllyasviel
1204d490d9 safer device 2024-02-06 05:01:58 -08:00
lllyasviel
9c31b0ddcb try fix #56 2024-02-06 04:51:08 -08:00
lllyasviel
6aee7a2032 Update forge_version.py 2024-02-05 23:55:27 -08:00
lllyasviel
74ff4a9ba9 set CUDA_VISIBLE_DEVICES with args 2024-02-05 23:53:11 -08:00
lllyasviel
1ecbff15fa add note about token merging 2024-02-05 21:55:59 -08:00
lllyasviel
7fd499a034 use new links for images if they were broken 2024-02-05 21:41:37 -08:00
lllyasviel
b8cd6d2e21 Update forge_version.py 2024-02-05 20:12:37 -08:00
lllyasviel
58dff34084 fix ddpm 2024-02-05 20:12:17 -08:00
Kohaku-Blueleaf
393c19bbcf Remove Lycoris back compact (#41)
Forge use totally different mechanism to handle lora/lycoris models
I think it is good to remove the back compact things so "lyco" alias can be used by legacy lycoris extensions. (some other extension may rely on it)
2024-02-06 11:17:15 +08:00
lllyasviel
b03df6fdb1 Update README.md 2024-02-05 17:59:37 -08:00
lllyasviel
f4e6794dbd Update README.md 2024-02-05 17:13:47 -08:00
lllyasviel
c5b51b35fb Update README.md 2024-02-05 15:50:44 -08:00
lllyasviel
218a10179b Update README.md 2024-02-05 15:48:57 -08:00
lllyasviel
4221ccf239 Update README.md 2024-02-05 15:45:03 -08:00
lllyasviel
53057f33ed Update forge_version.py 2024-02-05 15:30:45 -08:00
lllyasviel
7cef38e865 Update README.md 2024-02-05 15:17:13 -08:00
lllyasviel
b085ebd6db Update README.md 2024-02-05 15:16:14 -08:00
lllyasviel
28c4dd05d0 Update README.md 2024-02-05 15:14:09 -08:00
lllyasviel
88f6df4dcd add_sampler_pre_cfg_function 2024-02-05 14:48:43 -08:00
lllyasviel
8f86e66e5c Update README.md 2024-02-05 14:35:22 -08:00
lllyasviel
f2ceeaa4a9 Update README.md 2024-02-05 14:31:52 -08:00
lllyasviel
e2d85ff347 Update README.md 2024-02-05 14:26:19 -08:00
lllyasviel
2c95b09a73 Euler A Turbo 2024-02-05 14:23:42 -08:00
lllyasviel
7d1d04495f Update README.md 2024-02-05 14:15:36 -08:00
lllyasviel
d45066bef5 Update rng.py 2024-02-05 14:12:31 -08:00
lllyasviel
b174caa275 Update rng.py 2024-02-05 14:08:34 -08:00
lllyasviel
1b9734c45b Update rng.py 2024-02-05 13:50:19 -08:00
lllyasviel
8de4896bd6 fix inpaint formulation 2024-02-05 13:44:31 -08:00
lllyasviel
f5b3fcc6cf Update rng.py 2024-02-05 13:33:27 -08:00
lllyasviel
0ba407fd9c new samplers
DDPM
DDPM Karras
DPM++ 2M Turbo
DPM++ 2M SDE Turbo
LCM Karras
2024-02-05 03:58:06 -08:00
lllyasviel
af017121d2 Update forge_version.py 2024-02-05 01:31:24 -08:00
lllyasviel
40afb9dfb0 backend 2024-02-05 00:45:34 -08:00
lllyasviel
affb40340e infotext quickfix 2024-02-04 22:38:47 -08:00
lllyasviel
e02b69aa0c Update controlnet.py 2024-02-04 22:33:02 -08:00
lllyasviel
a4d64adb32 loop 2024-02-04 22:21:38 -08:00
lllyasviel
a8c43f7af0 batch support 2024-02-04 22:04:20 -08:00
lllyasviel
c6f7fa82ff ini batch 2024-02-04 21:43:17 -08:00
lllyasviel
4b6cd359e9 rename 2024-02-04 21:05:05 -08:00
lllyasviel
8dc2cb98b4 Update controlnet_ui_group.py 2024-02-04 20:50:07 -08:00
lllyasviel
a433268db4 register batch and multi input in unit 2024-02-04 20:49:40 -08:00
lllyasviel
858bfc7a32 Update unet_patcher.py 2024-02-04 19:40:21 -08:00
lllyasviel
fdbe5b7aa7 memory_peak_estimation_modifier 2024-02-04 19:36:58 -08:00
lllyasviel
bbdf53c79f Update README.md 2024-02-04 19:24:27 -08:00
hako-mikan
816096e642 Merge branch 'dev' into master 2023-11-09 21:57:57 +09:00
hako-mikan
6b9795849d Fix model switch bug 2023-11-09 20:23:37 +09:00
202 changed files with 6527 additions and 874 deletions

View File

@@ -1,4 +1,5 @@
extensions
extensions-disabled
extensions-builtin/sd_forge_controlnet
repositories
venv

View File

@@ -86,8 +86,6 @@ module.exports = {
// imageviewer.js
modalPrevImage: "readonly",
modalNextImage: "readonly",
// token-counters.js
setupTokenCounters: "readonly",
// localStorage.js
localSet: "readonly",
localGet: "readonly",

View File

@@ -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
View File

@@ -39,3 +39,6 @@ notification.mp3
/package-lock.json
/.coverage*
/test/test_outputs
/test/results.xml
coverage.xml
**/tests/**/expectations

111
README.md
View File

@@ -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.
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/1251ee5c-33dc-4adc-8dd3-2b43af5ad425)
Note that running `update.bat` is important, otherwise you may be using a previous version with potential bugs unfixed.
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/c49bd60d-82bd-4086-9859-88d472582b94)
# 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:**
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/c32baedd-500b-408f-8cfb-ed4570c883bd)
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/16893937-9ed9-4f8e-b960-70cd5d1e288f)
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/cb6098de-f2d4-4b25-9566-df4302dda396)
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/7bbc16fe-64ef-49e2-a595-d91bb658bd94)
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/5447e8b7-f3ca-4003-9961-02027c8181e8)
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/de1747fd-47bc-482d-a5c6-0728dd475943)
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/f3cb57d9-ac7a-4667-8b3f-303139e38afa)
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/96e5e171-2d74-41ba-9dcc-11bf68be7e16)
(average about 7.4GB/8GB, peak at about 7.9GB/8GB)
**This is WebUI Forge:**
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/0c45cd98-0b14-42c3-9556-28e48d4d5fa0)
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/ca5e05ed-bd86-4ced-8662-f41034648e8c)
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/3a71f5d4-39e5-4ab1-81cf-8eaa790a2dc8)
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/3629ee36-4a99-4d9b-b371-12efb260a283)
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/65fbb4a5-ee73-4bb9-9c5f-8a958cd9674d)
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/6d13ebb7-c30d-4aa8-9242-c0b5a1af8c95)
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/76f181a1-c5fb-4323-a6cc-b6308a45587e)
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/c4f723c3-6ea7-4539-980b-0708ed2a69aa)
(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:
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/a7798cf2-057c-43e0-883a-5f8643af8529)
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/277bac6e-5ea7-4bff-b71a-e55a60cfc03c)
Similar components like HyperTile, KohyaHighResFix, SAG, can all be implemented within 100 lines of codes (see also the codes).
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/e2fc1b73-e6ee-405e-864c-c67afd92a1db)
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/06472b03-b833-4816-ab47-70712ac024d3)
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.
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/ac7ed152-cd33-4645-94af-4c43bb8c3d88)
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/de1a2d05-344a-44d7-bab8-9ecc0a58a8d3)
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/cdcb23ad-02dc-4e39-be74-98e927550ef6)
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/14bcefcf-599f-42c3-bce9-3fd5e428dd91)
Similarly, Zero123:
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/d1a4a17d-f382-442d-91f2-fc5b6c10737f)
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/7685019c-7239-47fb-9cb5-2b7b33943285)
### Write a simple ControlNet:
@@ -526,7 +522,7 @@ if not cmd_opts.show_controlnet_example:
```
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/0a703d8b-27df-4608-8b12-aff750f20ffa)
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/822fa2fc-c9f4-4f58-8669-4b6680b91063)
### Add a preprocessor
@@ -626,29 +622,38 @@ Thanks to Unet Patcher, many new things are possible now and supported in Forge,
Masked Ip-Adapter
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/75432c4b-4f2a-4027-b6ad-fcf48fffad2c)
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/d26630f9-922d-4483-8bf9-f364dca5fd50)
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/c8dad060-9f93-4781-a14d-255180787592)
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/2680504e-6c7a-4531-b477-06e4c7b3ef3f)
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/03580ef7-235c-4b03-9ca6-a27677a5a175)
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/d9ed4a01-70d4-45b4-a6a7-2f765f158fae)
Masked ControlNet
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/1d74e970-fbe3-40df-9c87-70c8426ec6e1)
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/872d4785-60e4-4431-85c7-665c781dddaa)
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/0bc7bc7f-1a33-41c6-89ea-f5b5e60f6c1e)
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/335a3b33-1ef8-46ff-a462-9f1b4f2c49fc)
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/10b07d97-a2b8-463c-928a-5ad9b78da25e)
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/b3684a15-8895-414e-8188-487269dfcada)
PhotoMaker
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/377699d3-e6b5-4ace-9d0f-054ac1749fc8)
(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")
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/07b0b626-05b5-473b-9d69-3657624d59be)
Marigold Depth
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/95787c05-3fe7-43cc-ba12-baf378284007)
![image](https://github.com/lllyasviel/stable-diffusion-webui-forge/assets/19834515/bdf54148-892d-410d-8ed9-70b4b121b6e7)
# 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
@@ -669,3 +676,11 @@ Other extensions should work without problems, like:
However, if newer extensions use Forge, their codes can be much shorter.
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.

View File

@@ -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

View File

@@ -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

View File

@@ -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'))

View File

@@ -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()

View File

@@ -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)

View File

@@ -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"

View File

@@ -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)

View File

@@ -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",

View File

@@ -615,7 +615,8 @@ legacy_preprocessors = {
"priority": 100,
"tags": [
"MLSD"
]
],
"use_soft_projection_in_hr_fix": True
},
# "normal_bae": {
# "label": "normal_bae",

View File

@@ -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)

View File

@@ -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

View File

@@ -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']

View 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

View File

@@ -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:

View File

@@ -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"

View File

@@ -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"

View File

@@ -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):

View File

@@ -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:

View File

@@ -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}"

View File

@@ -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:

View File

@@ -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)

View 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")

Binary file not shown.

After

Width:  |  Height:  |  Size: 482 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 244 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 226 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 202 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@@ -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",
)

View File

@@ -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()

View 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,
}

View 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.

View File

@@ -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, )

View File

@@ -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

View File

@@ -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

View File

@@ -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)

View File

@@ -43,6 +43,8 @@ opFreeU_V2 = FreeU_V2()
class FreeUForForge(scripts.Script):
sorting_priority = 12
def title(self):
return "FreeU Integrated"

View File

@@ -8,6 +8,8 @@ opHyperTile = HyperTile()
class HyperTileForForge(scripts.Script):
sorting_priority = 13
def title(self):
return "HyperTile Integrated"

View File

@@ -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

View File

@@ -8,6 +8,8 @@ opPatchModelAddDownscale = PatchModelAddDownscale()
class KohyaHRFixForForge(scripts.Script):
sorting_priority = 14
def title(self):
return "Kohya HRFix Integrated"

View 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>.

View 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.

View File

@@ -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

View File

@@ -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,)

View File

@@ -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

View File

@@ -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

View File

@@ -8,6 +8,8 @@ opSelfAttentionGuidance = SelfAttentionGuidance()
class SAGForForge(scripts.Script):
sorting_priority = 12.5
def title(self):
return "SelfAttentionGuidance Integrated"

View File

@@ -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

View File

@@ -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)

View File

@@ -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)

View File

@@ -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));
}

View File

@@ -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();
}

View File

@@ -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;

View File

@@ -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');
}
});
});

View File

@@ -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;

View File

@@ -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);
});

View File

@@ -324,8 +324,6 @@ onAfterUiUpdate(function() {
});
json_elem.parentElement.style.display = "none";
setupTokenCounters();
});
onOptionsChanged(function() {

View File

@@ -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()

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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"]

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

Some files were not shown because too many files have changed in this diff Show More