From a09d7e39583c2c0b75db62de5bd388b4bb50a7f0 Mon Sep 17 00:00:00 2001 From: bmaltais Date: Thu, 7 Dec 2023 13:18:57 -0500 Subject: [PATCH 01/13] Update presets --- ...- lokr_v1.0.json => SDXL - LoKR v1.0.json} | 0 ...json => sd15 - EDG_LoConOptiSettings.json} | 0 ....json => sd15 - EDG_LoHaOptiSettings.json} | 0 ....json => sd15 - EDG_LoraOptiSettings.json} | 0 presets/lora/sd15 - LoKR v1.0.json | 100 ++++++++++++++++++ 5 files changed, 100 insertions(+) rename presets/lora/{SDXL - lokr_v1.0.json => SDXL - LoKR v1.0.json} (100%) rename presets/lora/{sd15-EDG_LoConOptiSettings.json => sd15 - EDG_LoConOptiSettings.json} (100%) rename presets/lora/{sd15-EDG_LoHaOptiSettings.json => sd15 - EDG_LoHaOptiSettings.json} (100%) rename presets/lora/{sd15-EDG_LoraOptiSettings.json => sd15 - EDG_LoraOptiSettings.json} (100%) create mode 100644 presets/lora/sd15 - LoKR v1.0.json diff --git a/presets/lora/SDXL - lokr_v1.0.json b/presets/lora/SDXL - LoKR v1.0.json similarity index 100% rename from presets/lora/SDXL - lokr_v1.0.json rename to presets/lora/SDXL - LoKR v1.0.json diff --git a/presets/lora/sd15-EDG_LoConOptiSettings.json b/presets/lora/sd15 - EDG_LoConOptiSettings.json similarity index 100% rename from presets/lora/sd15-EDG_LoConOptiSettings.json rename to presets/lora/sd15 - EDG_LoConOptiSettings.json diff --git a/presets/lora/sd15-EDG_LoHaOptiSettings.json b/presets/lora/sd15 - EDG_LoHaOptiSettings.json similarity index 100% rename from presets/lora/sd15-EDG_LoHaOptiSettings.json rename to presets/lora/sd15 - EDG_LoHaOptiSettings.json diff --git a/presets/lora/sd15-EDG_LoraOptiSettings.json b/presets/lora/sd15 - EDG_LoraOptiSettings.json similarity index 100% rename from presets/lora/sd15-EDG_LoraOptiSettings.json rename to presets/lora/sd15 - EDG_LoraOptiSettings.json diff --git a/presets/lora/sd15 - LoKR v1.0.json b/presets/lora/sd15 - LoKR v1.0.json new file mode 100644 index 000000000..ed4a272f8 --- /dev/null +++ b/presets/lora/sd15 - LoKR v1.0.json @@ -0,0 +1,100 @@ +{ + "LoRA_type": "LyCORIS/LoKr", + "LyCORIS_preset": "full", + "adaptive_noise_scale": 0.005, + "additional_parameters": "", + "block_alphas": "", + "block_dims": "", + "block_lr_zero_threshold": "", + "bucket_no_upscale": true, + "bucket_reso_steps": 1, + "cache_latents": true, + "cache_latents_to_disk": true, + "caption_dropout_every_n_epochs": 0.0, + "caption_dropout_rate": 0.05, + "caption_extension": ".txt", + "clip_skip": 1, + "color_aug": false, + "conv_alpha": 1, + "conv_block_alphas": "", + "conv_block_dims": "", + "conv_dim": 100000, + "debiased_estimation_loss": false, + "decompose_both": false, + "dim_from_weights": false, + "down_lr_weight": "", + "enable_bucket": true, + "epoch": 20, + "factor": 6, + "flip_aug": false, + "full_bf16": false, + "full_fp16": false, + "gradient_accumulation_steps": 1, + "gradient_checkpointing": false, + "keep_tokens": "0", + "learning_rate": 0.0001, + "lora_network_weights": "", + "lr_scheduler": "constant", + "lr_scheduler_args": "", + "lr_scheduler_num_cycles": "1", + "lr_scheduler_power": "", + "lr_warmup": 0, + "max_bucket_reso": 2048, + "max_data_loader_n_workers": "1", + "max_resolution": "768,768", + "max_timestep": 1000, + "max_token_length": "75", + "max_train_epochs": "", + "max_train_steps": "150", + "mem_eff_attn": false, + "mid_lr_weight": "", + "min_bucket_reso": 256, + "min_snr_gamma": 5, + "min_timestep": 0, + "mixed_precision": "bf16", + "module_dropout": 0, + "multires_noise_discount": 0.3, + "multires_noise_iterations": 10, + "network_alpha": 1, + "network_dim": 100000, + "network_dropout": 0, + "no_token_padding": false, + "noise_offset": 0, + "noise_offset_type": "Multires", + "num_cpu_threads_per_process": 2, + "optimizer": "AdamW", + "optimizer_args": "\"weight_decay=0.1\" \"betas=0.9,0.99\"", + "persistent_data_loader_workers": false, + "prior_loss_weight": 1.0, + "random_crop": false, + "rank_dropout": 0, + "save_every_n_epochs": 0, + "save_every_n_steps": 50, + "save_last_n_steps": 0, + "save_last_n_steps_state": 0, + "save_precision": "fp16", + "scale_v_pred_loss_like_noise_pred": false, + "scale_weight_norms": 1, + "sdxl": false, + "sdxl_cache_text_encoder_outputs": false, + "sdxl_no_half_vae": true, + "seed": "1234", + "shuffle_caption": false, + "stop_text_encoder_training": 0, + "text_encoder_lr": 0.0001, + "train_batch_size": 1, + "train_on_input": true, + "training_comment": "lxrssrrd woman", + "unet_lr": 0.0001, + "unit": 1, + "up_lr_weight": "", + "use_cp": false, + "use_wandb": false, + "v2": false, + "v_parameterization": false, + "v_pred_like_loss": 0, + "vae": "", + "vae_batch_size": 0, + "weighted_captions": false, + "xformers": "xformers" +} \ No newline at end of file From ec0eceb7402644b49c4e9c836726007e9f6f7b83 Mon Sep 17 00:00:00 2001 From: binit Date: Fri, 8 Dec 2023 23:37:30 +0000 Subject: [PATCH 02/13] Add goto page button * Help to navigate directly to a page instead of Prev/Next --- library/manual_caption_gui.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/library/manual_caption_gui.py b/library/manual_caption_gui.py index 826eb6762..69992a34c 100644 --- a/library/manual_caption_gui.py +++ b/library/manual_caption_gui.py @@ -49,6 +49,11 @@ def _get_tag_checkbox_updates(caption, quick_tags, quick_tags_set): def paginate(page, max_page, page_change): + try: + page = float(page) - 1 + except: + msgbox(f'Invalid page num: {page}') + return return int(max(min(page + page_change, max_page), 1)) @@ -313,6 +318,16 @@ def render_pagination(): outputs=[page], ) page_count = gr.Label('Page 1', label='Page') + page_goto_text = gr.Textbox( + label='Goto page', + placeholder='Page Number', + interactive=True, + ) + gr.Button('Go >', elem_id='open_folder').click( + paginate, + inputs=[page_goto_text, max_page, gr.Number(1, visible=False)], + outputs=[page], + ) gr.Button('Next >', elem_id='open_folder').click( paginate, inputs=[page, max_page, gr.Number(1, visible=False)], From d2f993bb093b58497fa8ede916bfae9174428190 Mon Sep 17 00:00:00 2001 From: binit-thapa Date: Sat, 9 Dec 2023 00:01:08 +0000 Subject: [PATCH 03/13] Fix and simplify code --- library/manual_caption_gui.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/library/manual_caption_gui.py b/library/manual_caption_gui.py index 69992a34c..cb9dd8136 100644 --- a/library/manual_caption_gui.py +++ b/library/manual_caption_gui.py @@ -48,12 +48,15 @@ def _get_tag_checkbox_updates(caption, quick_tags, quick_tags_set): ) -def paginate(page, max_page, page_change): +def paginate_go(page, max_page): try: - page = float(page) - 1 + page = float(page) except: msgbox(f'Invalid page num: {page}') return + return paginate(page, max_page, 0) + +def paginate(page, max_page, page_change): return int(max(min(page + page_change, max_page), 1)) @@ -324,8 +327,8 @@ def render_pagination(): interactive=True, ) gr.Button('Go >', elem_id='open_folder').click( - paginate, - inputs=[page_goto_text, max_page, gr.Number(1, visible=False)], + paginate_go, + inputs=[page_goto_text, max_page], outputs=[page], ) gr.Button('Next >', elem_id='open_folder').click( From 27cd481b1e20a635f685fdc4205f9b5b5cd227b4 Mon Sep 17 00:00:00 2001 From: bmaltais Date: Sun, 10 Dec 2023 16:12:13 -0500 Subject: [PATCH 04/13] Update LyCORIS options --- .release | 2 +- README.md | 49 +-- library/class_basic_training.py | 6 + library/common_gui.py | 5 + lora_gui.py | 611 +++++++++++++++++++++----------- 5 files changed, 430 insertions(+), 243 deletions(-) diff --git a/.release b/.release index d542ef359..6782a3f7d 100644 --- a/.release +++ b/.release @@ -1 +1 @@ -v22.3.0 +v22.3.1 diff --git a/README.md b/README.md index 14244a46e..0751ca275 100644 --- a/README.md +++ b/README.md @@ -202,8 +202,8 @@ This Colab notebook was not created or maintained by me; however, it appears to I would like to express my gratitude to camendutu for their valuable contribution. If you encounter any issues with the Colab notebook, please report them on their repository. -| Colab | Info | -| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------- | +| Colab | Info | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------ | | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/camenduru/kohya_ss-colab/blob/main/kohya_ss_colab.ipynb) | kohya_ss_gui_colab | ## Installation @@ -651,6 +651,11 @@ masterpiece, best quality, 1boy, in business suit, standing at street, looking b ## Change History +* 2023/12/10 (v22.3.1) +- Add goto button to manual caption utility +- Add missing options for various LyCORIS training algorythms +- Refactor how feilds are shown or hidden +- Made max value for network and convolution rank 512 except for LyCORIS/LoKr. * 2023/12/06 (v22.3.0) - Merge sd-scripts updates: - `finetune\tag_images_by_wd14_tagger.py` now supports the separator other than `,` with `--caption_separator` option. Thanks to KohakuBlueleaf! PR [#913](https://github.com/kohya-ss/sd-scripts/pull/913) @@ -664,42 +669,4 @@ masterpiece, best quality, 1boy, in business suit, standing at street, looking b - `--ds_ratio` option denotes the ratio of the Deep Shrink. `0.5` means the half of the original latent size for the Deep Shrink. - `--dst1`, `--dst2`, `--dsd1`, `--dsd2` and `--dsr` prompt options are also available. - Add GLoRA support - -* 2023/12/03 (v22.2.2) -- Update Lycoris module to 2.0.0 (https://github.com/KohakuBlueleaf/LyCORIS/blob/0006e2ffa05a48d8818112d9f70da74c0cd30b99/README.md) -- Update Lycoris merge and extract tools -- Remove anoying warning about local pip modules that is not necessary. -- Adding support for LyCORIS presets -- Adding Support for LyCORIS Native Fine-Tuning -- Adding support for Lycoris Diag-OFT - -* 2023/11/20 (v22.2.1) -- Fix issue with `Debiased Estimation loss` not getting properly loaded from json file. Oups. - -* 2023/11/15 (v22.2.0) -- sd-scripts code base update: - - `sdxl_train.py` now supports different learning rates for each Text Encoder. - - Example: - - `--learning_rate 1e-6`: train U-Net only - - `--train_text_encoder --learning_rate 1e-6`: train U-Net and two Text Encoders with the same learning rate (same as the previous version) - - `--train_text_encoder --learning_rate 1e-6 --learning_rate_te1 1e-6 --learning_rate_te2 1e-6`: train U-Net and two Text Encoders with the different learning rates - - `--train_text_encoder --learning_rate 0 --learning_rate_te1 1e-6 --learning_rate_te2 1e-6`: train two Text Encoders only - - `--train_text_encoder --learning_rate 1e-6 --learning_rate_te1 1e-6 --learning_rate_te2 0`: train U-Net and one Text Encoder only - - `--train_text_encoder --learning_rate 0 --learning_rate_te1 0 --learning_rate_te2 1e-6`: train one Text Encoder only - - - `train_db.py` and `fine_tune.py` now support different learning rates for Text Encoder. Specify with `--learning_rate_te` option. - - To train Text Encoder with `fine_tune.py`, specify `--train_text_encoder` option too. `train_db.py` trains Text Encoder by default. - - - Fixed the bug that Text Encoder is not trained when block lr is specified in `sdxl_train.py`. - - - Debiased Estimation loss is added to each training script. Thanks to sdbds! - - Specify `--debiased_estimation_loss` option to enable it. See PR [#889](https://github.com/kohya-ss/sd-scripts/pull/889) for details. - - Training of Text Encoder is improved in `train_network.py` and `sdxl_train_network.py`. Thanks to KohakuBlueleaf! PR [#895](https://github.com/kohya-ss/sd-scripts/pull/895) - - The moving average of the loss is now displayed in the progress bar in each training script. Thanks to shirayu! PR [#899](https://github.com/kohya-ss/sd-scripts/pull/899) - - PagedAdamW32bit optimizer is supported. Specify `--optimizer_type=PagedAdamW32bit`. Thanks to xzuyn! PR [#900](https://github.com/kohya-ss/sd-scripts/pull/900) - - Other bug fixes and improvements. -- kohya_ss gui updates: - - Implement GUI support for SDXL finetune TE1 and TE2 training LR parameters and for non SDXL finetune TE training parameter - - Implement GUI support for Dreambooth TE LR parameter - - Implement Debiased Estimation loss at the botom of the Advanced Parameters tab. - +- \ No newline at end of file diff --git a/library/class_basic_training.py b/library/class_basic_training.py index fe92501ef..e0bb2f1ef 100644 --- a/library/class_basic_training.py +++ b/library/class_basic_training.py @@ -115,6 +115,12 @@ def __init__( interactive=True, ) with gr.Row(): + self.max_grad_norm = gr.Slider( + label="Max grad norm", + value=1.0, + minimum=0.0, + maximum=1.0 + ) self.lr_scheduler_args = gr.Textbox( label="LR scheduler extra arguments", placeholder='(Optional) eg: "lr_end=5e-5"', diff --git a/library/common_gui.py b/library/common_gui.py index 3170c293d..9a1d69dd2 100644 --- a/library/common_gui.py +++ b/library/common_gui.py @@ -710,6 +710,11 @@ def run_cmd_training(**kwargs): lr_scheduler_args = kwargs.get('lr_scheduler_args', '') if lr_scheduler_args != '': run_cmd += f' --lr_scheduler_args {lr_scheduler_args}' + + max_grad_norm = kwargs.get('max_grad_norm', '') + if max_grad_norm != '': + run_cmd += f' --max_grad_norm="{max_grad_norm}"' + return run_cmd diff --git a/lora_gui.py b/lora_gui.py index 1a8199d0e..0298ebde4 100644 --- a/lora_gui.py +++ b/lora_gui.py @@ -125,7 +125,7 @@ def save_configuration( caption_dropout_rate, optimizer, optimizer_args, - lr_scheduler_args, + lr_scheduler_args,max_grad_norm, noise_offset_type, noise_offset, adaptive_noise_scale, @@ -133,7 +133,7 @@ def save_configuration( multires_noise_discount, LoRA_type, factor, - use_cp, + use_cp,use_tucker,use_scalar,rank_dropout_scale,constrain,rescaled,train_norm, decompose_both, train_on_input, conv_dim, @@ -280,7 +280,7 @@ def open_configuration( caption_dropout_rate, optimizer, optimizer_args, - lr_scheduler_args, + lr_scheduler_args,max_grad_norm, noise_offset_type, noise_offset, adaptive_noise_scale, @@ -288,7 +288,7 @@ def open_configuration( multires_noise_discount, LoRA_type, factor, - use_cp, + use_cp,use_tucker,use_scalar,rank_dropout_scale,constrain,rescaled,train_norm, decompose_both, train_on_input, conv_dim, @@ -455,7 +455,7 @@ def train_model( caption_dropout_rate, optimizer, optimizer_args, - lr_scheduler_args, + lr_scheduler_args,max_grad_norm, noise_offset_type, noise_offset, adaptive_noise_scale, @@ -463,7 +463,7 @@ def train_model( multires_noise_discount, LoRA_type, factor, - use_cp, + use_cp,use_tucker,use_scalar,rank_dropout_scale,constrain,rescaled,train_norm, decompose_both, train_on_input, conv_dim, @@ -721,7 +721,7 @@ def train_model( if not float(prior_loss_weight) == 1.0: run_cmd += f" --prior_loss_weight={prior_loss_weight}" - if LoRA_type == "LoCon" or LoRA_type == "LyCORIS/LoCon": + if LoRA_type == "LyCORIS/Diag-OFT": try: import lycoris except ModuleNotFoundError: @@ -730,9 +730,12 @@ def train_model( ) return run_cmd += f" --network_module=lycoris.kohya" - run_cmd += f' --network_args "preset={LyCORIS_preset}" "conv_dim={conv_dim}" "conv_alpha={conv_alpha}" "algo=locon"' + run_cmd += f' --network_args "preset={LyCORIS_preset}" "conv_dim={conv_dim}" "conv_alpha={conv_alpha}" "module_dropout={module_dropout}" "use_tucker={use_tucker}" "use_scalar={use_scalar}" "rank_dropout_scale={rank_dropout_scale}" "constrain={constrain}" "rescaled={rescaled}" "algo=diag-oft" ' + # This is a hack to fix a train_network LoHA logic issue + if not network_dropout > 0.0: + run_cmd += f' --network_dropout="{network_dropout}"' - if LoRA_type == "LyCORIS/GLoRA": + if LoRA_type == "LyCORIS/DyLoRA": try: import lycoris except ModuleNotFoundError: @@ -741,9 +744,12 @@ def train_model( ) return run_cmd += f" --network_module=lycoris.kohya" - run_cmd += f' --network_args "preset={LyCORIS_preset}" "conv_dim={conv_dim}" "conv_alpha={conv_alpha}" "algo=glora"' + run_cmd += f' --network_args "preset={LyCORIS_preset}" "conv_dim={conv_dim}" "conv_alpha={conv_alpha}" "use_tucker={use_tucker}" "block_size={unit}" "rank_dropout={rank_dropout}" "module_dropout={module_dropout}" "algo=dylora" "train_norm={train_norm}"' + # This is a hack to fix a train_network LoHA logic issue + if not network_dropout > 0.0: + run_cmd += f' --network_dropout="{network_dropout}"' - if LoRA_type == "LyCORIS/LoHa": + if LoRA_type == "LyCORIS/GLoRA": try: import lycoris except ModuleNotFoundError: @@ -752,10 +758,7 @@ def train_model( ) return run_cmd += f" --network_module=lycoris.kohya" - run_cmd += f' --network_args "preset={LyCORIS_preset}" "conv_dim={conv_dim}" "conv_alpha={conv_alpha}" "use_tucker={use_cp}" "algo=loha"' - # This is a hack to fix a train_network LoHA logic issue - if not network_dropout > 0.0: - run_cmd += f' --network_dropout="{network_dropout}"' + run_cmd += f' --network_args "preset={LyCORIS_preset}" "conv_dim={conv_dim}" "conv_alpha={conv_alpha}" "rank_dropout={rank_dropout}" "module_dropout={module_dropout}" "rank_dropout_scale={rank_dropout_scale}" "algo=glora" "train_norm={train_norm}"' if LoRA_type == "LyCORIS/iA3": try: @@ -771,7 +774,7 @@ def train_model( if not network_dropout > 0.0: run_cmd += f' --network_dropout="{network_dropout}"' - if LoRA_type == "LyCORIS/DyLoRA": + if LoRA_type == "LoCon" or LoRA_type == "LyCORIS/LoCon": try: import lycoris except ModuleNotFoundError: @@ -780,12 +783,12 @@ def train_model( ) return run_cmd += f" --network_module=lycoris.kohya" - run_cmd += f' --network_args "preset={LyCORIS_preset}" "conv_dim={conv_dim}" "conv_alpha={conv_alpha}" "use_cp={use_cp}" "block_size={unit}" "algo=dylora"' + run_cmd += f' --network_args "preset={LyCORIS_preset}" "conv_dim={conv_dim}" "conv_alpha={conv_alpha}" "rank_dropout={rank_dropout}" "module_dropout={module_dropout}" "use_tucker={use_tucker}" "use_scalar={use_scalar}" "rank_dropout_scale={rank_dropout_scale}" "algo=locon" "train_norm={train_norm}"' # This is a hack to fix a train_network LoHA logic issue if not network_dropout > 0.0: run_cmd += f' --network_dropout="{network_dropout}"' - if LoRA_type == "LyCORIS/LoKr": + if LoRA_type == "LyCORIS/LoHa": try: import lycoris except ModuleNotFoundError: @@ -794,12 +797,12 @@ def train_model( ) return run_cmd += f" --network_module=lycoris.kohya" - run_cmd += f' --network_args "preset={LyCORIS_preset}" "conv_dim={conv_dim}" "conv_alpha={conv_alpha}" "factor={factor}" "use_tucker={use_cp}" "algo=lokr"' + run_cmd += f' --network_args "preset={LyCORIS_preset}" "conv_dim={conv_dim}" "conv_alpha={conv_alpha}" "rank_dropout={rank_dropout}" "module_dropout={module_dropout}" "use_tucker={use_tucker}" "use_scalar={use_scalar}" "rank_dropout_scale={rank_dropout_scale}" "algo=loha" "train_norm={train_norm}"' # This is a hack to fix a train_network LoHA logic issue if not network_dropout > 0.0: run_cmd += f' --network_dropout="{network_dropout}"' - if LoRA_type == "LyCORIS/Native Fine-Tuning": + if LoRA_type == "LyCORIS/LoKr": try: import lycoris except ModuleNotFoundError: @@ -808,14 +811,12 @@ def train_model( ) return run_cmd += f" --network_module=lycoris.kohya" - run_cmd += ( - f' --network_args "preset={LyCORIS_preset}" "algo=full" "train_norm=True"' - ) + run_cmd += f' --network_args "preset={LyCORIS_preset}" "conv_dim={conv_dim}" "conv_alpha={conv_alpha}" "rank_dropout={rank_dropout}" "module_dropout={module_dropout}" "factor={factor}" "use_cp={use_cp}" "use_scalar={use_scalar}" "decompose_both={decompose_both}" "rank_dropout_scale={rank_dropout_scale}" "algo=lokr" "train_norm={train_norm}"' # This is a hack to fix a train_network LoHA logic issue if not network_dropout > 0.0: run_cmd += f' --network_dropout="{network_dropout}"' - if LoRA_type == "LyCORIS/Diag-OFT": + if LoRA_type == "LyCORIS/Native Fine-Tuning": try: import lycoris except ModuleNotFoundError: @@ -824,7 +825,9 @@ def train_model( ) return run_cmd += f" --network_module=lycoris.kohya" - run_cmd += f' --network_args "preset={LyCORIS_preset}" "algo=diag-oft" ' + run_cmd += ( + f' --network_args "preset={LyCORIS_preset}" "rank_dropout={rank_dropout}" "module_dropout={module_dropout}" "use_tucker={use_tucker}" "use_scalar={use_scalar}" "rank_dropout_scale={rank_dropout_scale}" "algo=full" "train_norm={train_norm}"' + ) # This is a hack to fix a train_network LoHA logic issue if not network_dropout > 0.0: run_cmd += f' --network_dropout="{network_dropout}"' @@ -999,6 +1002,7 @@ def train_model( optimizer=optimizer, optimizer_args=optimizer_args, lr_scheduler_args=lr_scheduler_args, + max_grad_norm=max_grad_norm, ) run_cmd += run_cmd_advanced_training( @@ -1235,9 +1239,46 @@ def list_presets(path): info="A two-step approach utilizing tensor decomposition and fine-tuning to accelerate convolution layers in large neural networks, resulting in significant CPU speedups with minor accuracy drops.", visible=False, ) + use_tucker = gr.Checkbox( + value=False, + label="Use Tucker decomposition", + info="Efficiently decompose tensor shapes, resulting in a sequence of convolution layers with varying dimensions and Hadamard product implementation through multiplication of two distinct tensors.", + visible=False, + ) + use_scalar = gr.Checkbox( + value=False, + label="Use Scalar", + info="Train an additional scalar in front of the weight difference, use a different weight initialization strategy.", + visible=False, + ) + rank_dropout_scale = gr.Checkbox( + value=False, + label="Rank Dropout Scale", + info="Adjusts the scale of the rank dropout to maintain the average dropout rate, ensuring more consistent regularization across different layers.", + visible=False, + ) + constrain = gr.Number( + value="0.0", + label="Constrain OFT", + info="Limits the norm of the oft_blocks, ensuring that their magnitude does not exceed a specified threshold, thus controlling the extent of the transformation applied.", + visible=False, + ) + rescaled = gr.Checkbox( + value=False, + label="Rescaled OFT", + info="applies an additional scaling factor to the oft_blocks, allowing for further adjustment of their impact on the model's transformations.", + visible=False, + ) + train_norm = gr.Checkbox( + value=False, + label="Train Norm", + info="Selects trainable layers in a network, but trains normalization layers identically across methods as they lack matrix decomposition.", + visible=False, + ) decompose_both = gr.Checkbox( value=False, label="LoKr decompose both", + info=" Controls whether both input and output dimensions of the layer's weights are decomposed into smaller matrices for reparameterization.", visible=False, ) train_on_input = gr.Checkbox( @@ -1246,10 +1287,10 @@ def list_presets(path): visible=False, ) - with gr.Row() as LoRA_dim_alpha: + with gr.Row() as network_row: network_dim = gr.Slider( minimum=1, - maximum=100000, # 512 if not LoRA_type == "LyCORIS/LoKr" else 100000, + maximum=512, label="Network Rank (Dimension)", value=8, step=1, @@ -1264,11 +1305,11 @@ def list_presets(path): interactive=True, info="alpha for LoRA weight scaling", ) - with gr.Row(visible=False) as LoCon_row: + with gr.Row(visible=False) as convolution_row: # locon= gr.Checkbox(label='Train a LoCon instead of a general LoRA (does not support v2 base models) (may not be able to some utilities now)', value=False) conv_dim = gr.Slider( minimum=0, - maximum=100000, # 512 if not LoRA_type == "LyCORIS/LoKr" else 100000, + maximum=512, value=1, step=1, label="Convolution Rank (Dimension)", @@ -1325,187 +1366,348 @@ def list_presets(path): ) # Show or hide LoCon conv settings depending on LoRA type selection - def update_LoRA_settings(LoRA_type): + def update_LoRA_settings( + LoRA_type, + conv_dim, + network_dim, + ): log.info("LoRA type changed...") - visibility_and_gr_types = { - "LoRA_dim_alpha": ( - { - "Kohya DyLoRA", - "Kohya LoCon", - "LoRA-FA", - "LyCORIS/Diag-OFT", - "LyCORIS/DyLoRA", - "LyCORIS/GLoRA", - "LyCORIS/LoCon", - "LyCORIS/LoHa", - "LyCORIS/LoKr", - "Standard", + lora_settings_config = { + "network_row": { + "gr_type": gr.Row, + "update_params": { + "visible": LoRA_type + in { + "Kohya DyLoRA", + "Kohya LoCon", + "LoRA-FA", + "LyCORIS/Diag-OFT", + "LyCORIS/DyLoRA", + "LyCORIS/GLoRA", + "LyCORIS/LoCon", + "LyCORIS/LoHa", + "LyCORIS/LoKr", + "Standard", + }, + }, + }, + "convolution_row": { + "gr_type": gr.Row, + "update_params": { + "visible": LoRA_type + in { + "LoCon", + "Kohya DyLoRA", + "Kohya LoCon", + "LoRA-FA", + "LyCORIS/Diag-OFT", + "LyCORIS/DyLoRA", + "LyCORIS/LoHa", + "LyCORIS/LoKr", + "LyCORIS/LoCon", + "LyCORIS/GLoRA", + }, + }, + }, + "kohya_advanced_lora": { + "gr_type": gr.Row, + "update_params": { + "visible": LoRA_type + in { + "Standard", + "Kohya DyLoRA", + "Kohya LoCon", + "LoRA-FA", + }, + }, + }, + "kohya_dylora": { + "gr_type": gr.Row, + "update_params": { + "visible": LoRA_type + in { + "Kohya DyLoRA", + "LyCORIS/DyLoRA", + }, + }, + }, + "lora_network_weights": { + "gr_type": gr.Textbox, + "update_params": { + "visible": LoRA_type + in { + "Standard", + "LoCon", + "Kohya DyLoRA", + "Kohya LoCon", + "LoRA-FA", + "LyCORIS/Diag-OFT", + "LyCORIS/DyLoRA", + "LyCORIS/GLoRA", + "LyCORIS/LoHa", + "LyCORIS/LoCon", + "LyCORIS/LoKr", + }, + }, + }, + "lora_network_weights_file": { + "gr_type": gr.Button, + "update_params": { + "visible": LoRA_type + in { + "Standard", + "LoCon", + "Kohya DyLoRA", + "Kohya LoCon", + "LoRA-FA", + "LyCORIS/Diag-OFT", + "LyCORIS/DyLoRA", + "LyCORIS/GLoRA", + "LyCORIS/LoHa", + "LyCORIS/LoCon", + "LyCORIS/LoKr", + }, + }, + }, + "dim_from_weights": { + "gr_type": gr.Checkbox, + "update_params": { + "visible": LoRA_type + in { + "Standard", + "LoCon", + "Kohya DyLoRA", + "Kohya LoCon", + "LoRA-FA", + "LyCORIS/Diag-OFT", + "LyCORIS/DyLoRA", + "LyCORIS/GLoRA", + "LyCORIS/LoHa", + "LyCORIS/LoCon", + "LyCORIS/LoKr", + } + }, + }, + "factor": { + "gr_type": gr.Slider, + "update_params": { + "visible": LoRA_type + in { + "LyCORIS/LoKr", + }, }, - gr.Row, - ), - "LoCon_row": ( - { - "LoCon", - "Kohya DyLoRA", - "Kohya LoCon", - "LoRA-FA", - "LyCORIS/Diag-OFT", - "LyCORIS/DyLoRA", - "LyCORIS/LoHa", - "LyCORIS/LoKr", - "LyCORIS/LoCon", - "LyCORIS/GLoRA", + }, + "conv_dim": { + "gr_type": gr.Slider, + "update_params": { + "maximum": 100000 + if LoRA_type in {"LyCORIS/LoHa", "LyCORIS/LoKr", "LyCORIS/Diag-OFT"} + else 512, + "value": 512 if conv_dim > 512 else conv_dim, }, - gr.Row, - ), - "kohya_advanced_lora": ( - { - "Standard", - "Kohya DyLoRA", - "Kohya LoCon", - "LoRA-FA", + }, + "network_dim": { + "gr_type": gr.Slider, + "update_params": { + "maximum": 100000 + if LoRA_type in {"LyCORIS/LoHa", "LyCORIS/LoKr", "LyCORIS/Diag-OFT"} + else 512, + "value": 512 if network_dim > 512 else network_dim, }, - gr.Row, - ), - "kohya_dylora": ( - {"Kohya DyLoRA", "LyCORIS/DyLoRA"}, - gr.Row, - ), - "lora_network_weights": ( - { - "Standard", - "LoCon", - "Kohya DyLoRA", - "Kohya LoCon", - "LoRA-FA", - "LyCORIS/Diag-OFT", - "LyCORIS/DyLoRA", - "LyCORIS/GLoRA", - "LyCORIS/LoHa", - "LyCORIS/LoCon", - "LyCORIS/LoKr", + }, + "use_cp": { + "gr_type": gr.Checkbox, + "update_params": { + "visible": LoRA_type + in { + "LyCORIS/LoKr", + }, }, - gr.Textbox, - ), - "lora_network_weights_file": ( - { - "Standard", - "LoCon", - "Kohya DyLoRA", - "Kohya LoCon", - "LoRA-FA", - "LyCORIS/Diag-OFT", - "LyCORIS/DyLoRA", - "LyCORIS/GLoRA", - "LyCORIS/LoHa", - "LyCORIS/LoCon", - "LyCORIS/LoKr", + }, + "use_tucker": { + "gr_type": gr.Checkbox, + "update_params": { + "visible": LoRA_type + in { + "LyCORIS/Diag-OFT", + "LyCORIS/DyLoRA", + "LyCORIS/LoCon", + "LyCORIS/LoHa", + "LyCORIS/Native Fine-Tuning", + }, }, - gr.Button, - ), - "dim_from_weights": ( - { - "Standard", - "LoCon", - "Kohya DyLoRA", - "Kohya LoCon", - "LoRA-FA", - "LyCORIS/Diag-OFT", - "LyCORIS/DyLoRA", - "LyCORIS/GLoRA", - "LyCORIS/LoHa", - "LyCORIS/LoCon", - "LyCORIS/LoKr", + }, + "use_scalar": { + "gr_type": gr.Checkbox, + "update_params": { + "visible": LoRA_type + in { + "LyCORIS/Diag-OFT", + "LyCORIS/LoCon", + "LyCORIS/LoHa", + "LyCORIS/LoKr", + "LyCORIS/Native Fine-Tuning", + }, }, - gr.Checkbox, - ), - "factor": ({"LyCORIS/LoKr"}, gr.Slider), - "use_cp": ( - { - "LyCORIS/DyLoRA", - "LyCORIS/LoHa", - "LyCORIS/GLoRA", - "LyCORIS/LoCon", - "LyCORIS/LoKr", + }, + "rank_dropout_scale": { + "gr_type": gr.Checkbox, + "update_params": { + "visible": LoRA_type + in { + "LyCORIS/Diag-OFT", + "LyCORIS/GLoRA", + "LyCORIS/LoCon", + "LyCORIS/LoHa", + "LyCORIS/LoKr", + "LyCORIS/Native Fine-Tuning", + }, }, - gr.Checkbox, - ), - "decompose_both": ({"LyCORIS/LoKr"}, gr.Checkbox), - "train_on_input": ({"LyCORIS/iA3"}, gr.Checkbox), - "scale_weight_norms": ( - { - "LoCon", - "Kohya DyLoRA", - "Kohya LoCon", - "LoRA-FA", - "LyCORIS/DyLoRA", - "LyCORIS/GLoRA", - "LyCORIS/LoHa", - "LyCORIS/LoCon", - "LyCORIS/LoKr", - "Standard", + }, + "constrain": { + "gr_type": gr.Number, + "update_params": { + "visible": LoRA_type + in { + "LyCORIS/Diag-OFT", + }, }, - gr.Slider, - ), - "network_dropout": ( - { - "LoCon", - "Kohya DyLoRA", - "Kohya LoCon", - "LoRA-FA", - "LyCORIS/Diag-OFT", - "LyCORIS/DyLoRA", - "LyCORIS/GLoRA", - "LyCORIS/LoHa", - "LyCORIS/LoCon", - "LyCORIS/LoKr", - "Standard", + }, + "rescaled": { + "gr_type": gr.Checkbox, + "update_params": { + "visible": LoRA_type + in { + "LyCORIS/Diag-OFT", + }, }, - gr.Slider, - ), - "rank_dropout": ( - { - "LoCon", - "Kohya DyLoRA", - "Kohya LoCon", - "LoRA-FA", - "Standard", + }, + "train_norm": { + "gr_type": gr.Checkbox, + "update_params": { + "visible": LoRA_type + in { + "LyCORIS/DyLoRA", + "LyCORIS/Diag-OFT", + "LyCORIS/GLoRA", + "LyCORIS/LoCon", + "LyCORIS/LoHa", + "LyCORIS/LoKr", + "LyCORIS/Native Fine-Tuning", + }, }, - gr.Slider, - ), - "module_dropout": ( - { - "LoCon", - "Kohya DyLoRA", - "Kohya LoCon", - "LoRA-FA", - "Standard", + }, + "decompose_both": { + "gr_type": gr.Checkbox, + "update_params": { + "visible": LoRA_type in {"LyCORIS/LoKr"}, }, - gr.Slider, - ), - "LyCORIS_preset": ( - { - "LyCORIS/DyLoRA", - "LyCORIS/iA3", - "LyCORIS/Diag-OFT", - "LyCORIS/GLoRA", - "LyCORIS/LoCon", - "LyCORIS/LoHa", - "LyCORIS/LoKr", - "LyCORIS/Native Fine-Tuning", + }, + "train_on_input": { + "gr_type": gr.Checkbox, + "update_params": { + "visible": LoRA_type in {"LyCORIS/iA3"}, }, - gr.Dropdown, - ), + }, + "scale_weight_norms": { + "gr_type": gr.Slider, + "update_params": { + "visible": LoRA_type + in { + "LoCon", + "Kohya DyLoRA", + "Kohya LoCon", + "LoRA-FA", + "LyCORIS/DyLoRA", + "LyCORIS/GLoRA", + "LyCORIS/LoHa", + "LyCORIS/LoCon", + "LyCORIS/LoKr", + "Standard", + }, + }, + }, + "network_dropout": { + "gr_type": gr.Slider, + "update_params": { + "visible": LoRA_type + in { + "LoCon", + "Kohya DyLoRA", + "Kohya LoCon", + "LoRA-FA", + "LyCORIS/Diag-OFT", + "LyCORIS/DyLoRA", + "LyCORIS/GLoRA", + "LyCORIS/LoCon", + "LyCORIS/LoHa", + "LyCORIS/LoKr", + "LyCORIS/Native Fine-Tuning", + "Standard", + }, + }, + }, + "rank_dropout": { + "gr_type": gr.Slider, + "update_params": { + "visible": LoRA_type + in { + "LoCon", + "Kohya DyLoRA", + "LyCORIS/GLoRA", + "LyCORIS/LoCon", + "LyCORIS/LoHa", + "LyCORIS/LoKR", + "Kohya LoCon", + "LoRA-FA", + "LyCORIS/Native Fine-Tuning", + "Standard", + }, + }, + }, + "module_dropout": { + "gr_type": gr.Slider, + "update_params": { + "visible": LoRA_type + in { + "LoCon", + "LyCORIS/Diag-OFT", + "Kohya DyLoRA", + "LyCORIS/GLoRA", + "LyCORIS/LoCon", + "LyCORIS/LoHa", + "LyCORIS/LoKR", + "Kohya LoCon", + "LyCORIS/Native Fine-Tuning", + "LoRA-FA", + "Standard", + }, + }, + }, + "LyCORIS_preset": { + "gr_type": gr.Dropdown, + "update_params": { + "visible": LoRA_type + in { + "LyCORIS/DyLoRA", + "LyCORIS/iA3", + "LyCORIS/Diag-OFT", + "LyCORIS/GLoRA", + "LyCORIS/LoCon", + "LyCORIS/LoHa", + "LyCORIS/LoKr", + "LyCORIS/Native Fine-Tuning", + }, + }, + }, } results = [] - for attr, ( - visibility, - gr_type, - ) in visibility_and_gr_types.items(): - visible = LoRA_type in visibility - results.append(gr_type.update(visible=visible)) + for attr, settings in lora_settings_config.items(): + update_params = settings["update_params"] + + results.append(settings["gr_type"].update(**update_params)) return tuple(results) @@ -1570,17 +1772,23 @@ def update_LoRA_settings(LoRA_type): LoRA_type.change( update_LoRA_settings, - inputs=[LoRA_type], + inputs=[ + LoRA_type, + conv_dim, + network_dim, + ], outputs=[ - LoRA_dim_alpha, - LoCon_row, + network_row, + convolution_row, kohya_advanced_lora, kohya_dylora, lora_network_weights, lora_network_weights_file, dim_from_weights, factor, - use_cp, + conv_dim, + network_dim, + use_cp,use_tucker,use_scalar,rank_dropout_scale,constrain,rescaled,train_norm, decompose_both, train_on_input, scale_weight_norms, @@ -1695,6 +1903,7 @@ def update_LoRA_settings(LoRA_type): basic_training.optimizer, basic_training.optimizer_args, basic_training.lr_scheduler_args, + basic_training.max_grad_norm, advanced_training.noise_offset_type, advanced_training.noise_offset, advanced_training.adaptive_noise_scale, @@ -1702,7 +1911,7 @@ def update_LoRA_settings(LoRA_type): advanced_training.multires_noise_discount, LoRA_type, factor, - use_cp, + use_cp,use_tucker,use_scalar,rank_dropout_scale,constrain,rescaled,train_norm, decompose_both, train_on_input, conv_dim, @@ -1751,7 +1960,7 @@ def update_LoRA_settings(LoRA_type): + [training_preset], outputs=[config.config_file_name] + settings_list - + [training_preset, LoCon_row], + + [training_preset, convolution_row], show_progress=False, ) @@ -1762,7 +1971,7 @@ def update_LoRA_settings(LoRA_type): + [training_preset], outputs=[config.config_file_name] + settings_list - + [training_preset, LoCon_row], + + [training_preset, convolution_row], show_progress=False, ) @@ -1771,7 +1980,7 @@ def update_LoRA_settings(LoRA_type): inputs=[dummy_db_false, dummy_db_true, config.config_file_name] + settings_list + [training_preset], - outputs=[gr.Textbox()] + settings_list + [training_preset, LoCon_row], + outputs=[gr.Textbox()] + settings_list + [training_preset, convolution_row], show_progress=False, ) From 161b8b486f5879973d3cec5b186bf95e173b11a6 Mon Sep 17 00:00:00 2001 From: bmaltais Date: Sun, 10 Dec 2023 21:13:50 -0500 Subject: [PATCH 05/13] Update presets --- lora_gui.py | 1 + presets/lora/sd15 - GLoRA v1.0.json | 107 ++++++++++++++++++++++++++++ presets/lora/sd15 - LoKr v1.1.json | 107 ++++++++++++++++++++++++++++ 3 files changed, 215 insertions(+) create mode 100644 presets/lora/sd15 - GLoRA v1.0.json create mode 100644 presets/lora/sd15 - LoKr v1.1.json diff --git a/lora_gui.py b/lora_gui.py index 0298ebde4..182f05df5 100644 --- a/lora_gui.py +++ b/lora_gui.py @@ -1284,6 +1284,7 @@ def list_presets(path): train_on_input = gr.Checkbox( value=True, label="iA3 train on input", + info="Set if we change the information going into the system (True) or the information coming out of it (False)." visible=False, ) diff --git a/presets/lora/sd15 - GLoRA v1.0.json b/presets/lora/sd15 - GLoRA v1.0.json new file mode 100644 index 000000000..bf63a4fb8 --- /dev/null +++ b/presets/lora/sd15 - GLoRA v1.0.json @@ -0,0 +1,107 @@ +{ + "LoRA_type": "LyCORIS/LoKr", + "LyCORIS_preset": "full", + "adaptive_noise_scale": 0.005, + "additional_parameters": "", + "block_alphas": "", + "block_dims": "", + "block_lr_zero_threshold": "", + "bucket_no_upscale": true, + "bucket_reso_steps": 1, + "cache_latents": true, + "cache_latents_to_disk": true, + "caption_dropout_every_n_epochs": 0, + "caption_dropout_rate": 0.05, + "caption_extension": ".txt", + "clip_skip": 1, + "color_aug": false, + "constrain": 0, + "conv_alpha": 1, + "conv_block_alphas": "", + "conv_block_dims": "", + "conv_dim": 100000, + "debiased_estimation_loss": false, + "decompose_both": true, + "dim_from_weights": false, + "down_lr_weight": "", + "enable_bucket": true, + "epoch": 20, + "factor": 6, + "flip_aug": false, + "full_bf16": false, + "full_fp16": false, + "gradient_accumulation_steps": 1, + "gradient_checkpointing": false, + "keep_tokens": "0", + "learning_rate": 0.0001, + "lora_network_weights": "", + "lr_scheduler": "constant", + "lr_scheduler_args": "", + "lr_scheduler_num_cycles": "1", + "lr_scheduler_power": "", + "lr_warmup": 0, + "max_bucket_reso": 2048, + "max_data_loader_n_workers": "1", + "max_grad_norm": 1, + "max_resolution": "768,768", + "max_timestep": 1000, + "max_token_length": "75", + "max_train_epochs": "", + "max_train_steps": "113", + "mem_eff_attn": false, + "mid_lr_weight": "", + "min_bucket_reso": 256, + "min_snr_gamma": 5, + "min_timestep": 0, + "mixed_precision": "bf16", + "module_dropout": 0, + "multires_noise_discount": 0.3, + "multires_noise_iterations": 10, + "network_alpha": 1, + "network_dim": 100000, + "network_dropout": 0, + "no_token_padding": false, + "noise_offset": 0, + "noise_offset_type": "Multires", + "num_cpu_threads_per_process": 2, + "optimizer": "AdamW", + "optimizer_args": "\"weight_decay=0.1\" \"betas=0.9,0.99\"", + "persistent_data_loader_workers": false, + "prior_loss_weight": 1, + "random_crop": false, + "rank_dropout": 0, + "rank_dropout_scale": true, + "rescaled": false, + "save_every_n_epochs": 0, + "save_every_n_steps": 29, + "save_last_n_steps": 0, + "save_last_n_steps_state": 0, + "save_precision": "fp16", + "scale_v_pred_loss_like_noise_pred": false, + "scale_weight_norms": 1, + "sdxl": false, + "sdxl_cache_text_encoder_outputs": false, + "sdxl_no_half_vae": true, + "seed": "1234", + "shuffle_caption": false, + "stop_text_encoder_training": 0, + "text_encoder_lr": 0.0001, + "train_batch_size": 1, + "train_norm": true, + "train_on_input": true, + "training_comment": "busty blonde woman full", + "unet_lr": 0.0001, + "unit": 1, + "up_lr_weight": "", + "use_cp": true, + "use_scalar": false, + "use_tucker": false, + "use_wandb": false, + "v2": false, + "v_parameterization": false, + "v_pred_like_loss": 0, + "vae": "", + "vae_batch_size": 0, + "weighted_captions": false, + "xformers": "xformers" +} \ No newline at end of file diff --git a/presets/lora/sd15 - LoKr v1.1.json b/presets/lora/sd15 - LoKr v1.1.json new file mode 100644 index 000000000..bf63a4fb8 --- /dev/null +++ b/presets/lora/sd15 - LoKr v1.1.json @@ -0,0 +1,107 @@ +{ + "LoRA_type": "LyCORIS/LoKr", + "LyCORIS_preset": "full", + "adaptive_noise_scale": 0.005, + "additional_parameters": "", + "block_alphas": "", + "block_dims": "", + "block_lr_zero_threshold": "", + "bucket_no_upscale": true, + "bucket_reso_steps": 1, + "cache_latents": true, + "cache_latents_to_disk": true, + "caption_dropout_every_n_epochs": 0, + "caption_dropout_rate": 0.05, + "caption_extension": ".txt", + "clip_skip": 1, + "color_aug": false, + "constrain": 0, + "conv_alpha": 1, + "conv_block_alphas": "", + "conv_block_dims": "", + "conv_dim": 100000, + "debiased_estimation_loss": false, + "decompose_both": true, + "dim_from_weights": false, + "down_lr_weight": "", + "enable_bucket": true, + "epoch": 20, + "factor": 6, + "flip_aug": false, + "full_bf16": false, + "full_fp16": false, + "gradient_accumulation_steps": 1, + "gradient_checkpointing": false, + "keep_tokens": "0", + "learning_rate": 0.0001, + "lora_network_weights": "", + "lr_scheduler": "constant", + "lr_scheduler_args": "", + "lr_scheduler_num_cycles": "1", + "lr_scheduler_power": "", + "lr_warmup": 0, + "max_bucket_reso": 2048, + "max_data_loader_n_workers": "1", + "max_grad_norm": 1, + "max_resolution": "768,768", + "max_timestep": 1000, + "max_token_length": "75", + "max_train_epochs": "", + "max_train_steps": "113", + "mem_eff_attn": false, + "mid_lr_weight": "", + "min_bucket_reso": 256, + "min_snr_gamma": 5, + "min_timestep": 0, + "mixed_precision": "bf16", + "module_dropout": 0, + "multires_noise_discount": 0.3, + "multires_noise_iterations": 10, + "network_alpha": 1, + "network_dim": 100000, + "network_dropout": 0, + "no_token_padding": false, + "noise_offset": 0, + "noise_offset_type": "Multires", + "num_cpu_threads_per_process": 2, + "optimizer": "AdamW", + "optimizer_args": "\"weight_decay=0.1\" \"betas=0.9,0.99\"", + "persistent_data_loader_workers": false, + "prior_loss_weight": 1, + "random_crop": false, + "rank_dropout": 0, + "rank_dropout_scale": true, + "rescaled": false, + "save_every_n_epochs": 0, + "save_every_n_steps": 29, + "save_last_n_steps": 0, + "save_last_n_steps_state": 0, + "save_precision": "fp16", + "scale_v_pred_loss_like_noise_pred": false, + "scale_weight_norms": 1, + "sdxl": false, + "sdxl_cache_text_encoder_outputs": false, + "sdxl_no_half_vae": true, + "seed": "1234", + "shuffle_caption": false, + "stop_text_encoder_training": 0, + "text_encoder_lr": 0.0001, + "train_batch_size": 1, + "train_norm": true, + "train_on_input": true, + "training_comment": "busty blonde woman full", + "unet_lr": 0.0001, + "unit": 1, + "up_lr_weight": "", + "use_cp": true, + "use_scalar": false, + "use_tucker": false, + "use_wandb": false, + "v2": false, + "v_parameterization": false, + "v_pred_like_loss": 0, + "vae": "", + "vae_batch_size": 0, + "weighted_captions": false, + "xformers": "xformers" +} \ No newline at end of file From ca6661fcf1f02e75997aa4fee62f54ae226d2b0b Mon Sep 17 00:00:00 2001 From: Raaf <35073307+tjip1234@users.noreply.github.com> Date: Tue, 12 Dec 2023 14:02:52 +0100 Subject: [PATCH 06/13] Update requirements.txt --- requirements.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/requirements.txt b/requirements.txt index ffc2e3880..08529ea3d 100644 --- a/requirements.txt +++ b/requirements.txt @@ -40,5 +40,6 @@ toml==0.10.2 transformers==4.30.2 voluptuous==0.13.1 wandb==0.15.11 +scipy==1.11.4 # for kohya_ss library -e . # no_verify leave this to specify not checking this a verification stage From 2e37d0de4ca3f08dfc49213a1da1adaa3d789f91 Mon Sep 17 00:00:00 2001 From: bmaltais Date: Tue, 12 Dec 2023 10:38:16 -0500 Subject: [PATCH 07/13] Add support to conver model to LCM model --- library/class_lora_tab.py | 2 + library/convert_lcm_gui.py | 118 +++++++++++++++++++++++++++++++++++++ lora_gui.py | 2 +- requirements.txt | 5 +- setup.bat | 2 +- tools/lcm_convert.py | 73 +++++++++++++++++++++++ 6 files changed, 198 insertions(+), 4 deletions(-) create mode 100644 library/convert_lcm_gui.py create mode 100644 tools/lcm_convert.py diff --git a/library/class_lora_tab.py b/library/class_lora_tab.py index 823993a5a..df6a4f387 100644 --- a/library/class_lora_tab.py +++ b/library/class_lora_tab.py @@ -4,6 +4,7 @@ from library.verify_lora_gui import gradio_verify_lora_tab from library.resize_lora_gui import gradio_resize_lora_tab from library.extract_lora_gui import gradio_extract_lora_tab +from library.convert_lcm_gui import gradio_convert_lcm_tab from library.extract_lycoris_locon_gui import gradio_extract_lycoris_locon_tab from library.extract_lora_from_dylora_gui import gradio_extract_dylora_tab from library.merge_lycoris_gui import gradio_merge_lycoris_tab @@ -24,6 +25,7 @@ def __init__(self, folders='', headless: bool = False): 'This section provide LoRA tools to help setup your dataset...' ) gradio_extract_dylora_tab(headless=headless) + gradio_convert_lcm_tab(headless=headless) gradio_extract_lora_tab(headless=headless) gradio_extract_lycoris_locon_tab(headless=headless) gradio_merge_lora_tab = GradioMergeLoRaTab() diff --git a/library/convert_lcm_gui.py b/library/convert_lcm_gui.py new file mode 100644 index 000000000..41b01fc54 --- /dev/null +++ b/library/convert_lcm_gui.py @@ -0,0 +1,118 @@ +import gradio as gr +import os +import subprocess +from .common_gui import ( + get_saveasfilename_path, + get_file_path, +) +from library.custom_logging import setup_logging + +# Set up logging +log = setup_logging() + +folder_symbol = "\U0001f4c2" # 📂 +refresh_symbol = "\U0001f504" # 🔄 +save_style_symbol = "\U0001f4be" # 💾 +document_symbol = "\U0001F4C4" # 📄 + +PYTHON = "python3" if os.name == "posix" else "./venv/Scripts/python.exe" + + +def convert_lcm( + name, + model_path, + lora_scale, + model_type +): + run_cmd = f'{PYTHON} "{os.path.join("tools","lcm_convert.py")}"' + # Construct the command to run the script + run_cmd += f' --name "{name}"' + run_cmd += f' --model "{model_path}"' + run_cmd += f" --lora-scale {lora_scale}" + + if model_type == "SDXL": + run_cmd += f" --sdxl" + if model_type == "SSD-1B": + run_cmd += f" --ssd-1b" + + log.info(run_cmd) + + # Run the command + if os.name == "posix": + os.system(run_cmd) + else: + subprocess.run(run_cmd) + + # Return a success message + log.info("Done extracting...") + + +def gradio_convert_lcm_tab(headless=False): + with gr.Tab("Convert to LCM"): + gr.Markdown("This utility convert a model to an LCM model.") + lora_ext = gr.Textbox(value="*.safetensors", visible=False) + lora_ext_name = gr.Textbox(value="LCM model types", visible=False) + model_ext = gr.Textbox(value="*.safetensors", visible=False) + model_ext_name = gr.Textbox(value="Model types", visible=False) + + with gr.Row(): + model_path = gr.Textbox( + label="Stable Diffusion model to convert to LCM", + interactive=True, + ) + button_model_path_file = gr.Button( + folder_symbol, + elem_id="open_folder_small", + visible=(not headless), + ) + button_model_path_file.click( + get_file_path, + inputs=[model_path, model_ext, model_ext_name], + outputs=model_path, + show_progress=False, + ) + + name = gr.Textbox( + label="Name of the new LCM model", + placeholder="Path to the LCM file to create", + interactive=True, + ) + button_name = gr.Button( + folder_symbol, + elem_id="open_folder_small", + visible=(not headless), + ) + button_name.click( + get_saveasfilename_path, + inputs=[name, lora_ext, lora_ext_name], + outputs=name, + show_progress=False, + ) + + with gr.Row(): + lora_scale = gr.Slider( + label="Strength of the LCM", + minimum=0.0, + maximum=2.0, + step=0.1, + value=1.0, + interactive=True, + ) + # with gr.Row(): + # no_half = gr.Checkbox(label="Convert the new LCM model to FP32", value=False) + model_type = gr.Dropdown( + label="Model type", choices=["SD15", "SDXL", "SD-1B"], value="SD15" + ) + + extract_button = gr.Button("Extract LCM") + + extract_button.click( + convert_lcm, + inputs=[ + name, + model_path, + lora_scale, + model_type + ], + show_progress=False, + ) diff --git a/lora_gui.py b/lora_gui.py index 182f05df5..baf34b4af 100644 --- a/lora_gui.py +++ b/lora_gui.py @@ -1284,7 +1284,7 @@ def list_presets(path): train_on_input = gr.Checkbox( value=True, label="iA3 train on input", - info="Set if we change the information going into the system (True) or the information coming out of it (False)." + info="Set if we change the information going into the system (True) or the information coming out of it (False).", visible=False, ) diff --git a/requirements.txt b/requirements.txt index ffc2e3880..a75c2401c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,13 +3,13 @@ accelerate==0.23.0 aiofiles==23.2.1 altair==4.2.2 dadaptation==3.1 -diffusers[torch]==0.21.4 +diffusers[torch]==0.24.0 easygui==0.98.3 einops==0.6.0 fairscale==0.4.13 ftfy==6.1.1 gradio==3.36.1 -huggingface-hub==0.15.1 +huggingface-hub==0.19.4 # for loading Diffusers' SDXL invisible-watermark==0.2.0 lion-pytorch==0.0.6 @@ -21,6 +21,7 @@ lycoris_lora==2.0.0 # for WD14 captioning (tensorflow) # tensorflow==2.14.0 # for WD14 captioning (onnx) +omegaconf==2.3.0 onnx==1.14.1 onnxruntime-gpu==1.16.0 # onnxruntime==1.16.0 diff --git a/setup.bat b/setup.bat index dc68cbd34..d88cfaffc 100644 --- a/setup.bat +++ b/setup.bat @@ -20,7 +20,7 @@ mkdir ".\logs\setup" > nul 2>&1 call .\venv\Scripts\deactivate.bat :: Calling external python program to check for local modules -python .\setup\check_local_modules.py +:: python .\setup\check_local_modules.py call .\venv\Scripts\activate.bat diff --git a/tools/lcm_convert.py b/tools/lcm_convert.py new file mode 100644 index 000000000..1fc39f69d --- /dev/null +++ b/tools/lcm_convert.py @@ -0,0 +1,73 @@ +import argparse +import torch +from library.custom_logging import setup_logging +from diffusers import StableDiffusionPipeline, StableDiffusionXLPipeline, LCMScheduler +from library.sdxl_model_util import convert_diffusers_unet_state_dict_to_sdxl, sdxl_original_unet, save_stable_diffusion_checkpoint, _load_state_dict_on_device as load_state_dict_on_device +from accelerate import init_empty_weights + +# Initialize logging +logger = setup_logging() + +def parse_command_line_arguments(): + argument_parser = argparse.ArgumentParser("lcm_convert") + argument_parser.add_argument("--name", help="Name of the new LCM model", required=True, type=str) + argument_parser.add_argument("--model", help="A model to convert", required=True, type=str) + argument_parser.add_argument("--lora-scale", default=1.0, help="Strength of the LCM", type=float) + argument_parser.add_argument("--sdxl", action="store_true", help="Use SDXL models") + argument_parser.add_argument("--ssd-1b", action="store_true", help="Use SSD-1B models") + return argument_parser.parse_args() + +def load_diffusion_pipeline(command_line_args): + if command_line_args.sdxl or command_line_args.ssd_1b: + return StableDiffusionXLPipeline.from_single_file(command_line_args.model) + else: + return StableDiffusionPipeline.from_single_file(command_line_args.model) + +def convert_and_save_diffusion_model(diffusion_pipeline, command_line_args): + diffusion_pipeline.scheduler = LCMScheduler.from_config(diffusion_pipeline.scheduler.config) + lora_weight_file_path = "latent-consistency/lcm-lora-" + ("sdxl" if command_line_args.sdxl else "ssd-1b" if command_line_args.ssd_1b else "sdv1-5") + diffusion_pipeline.load_lora_weights(lora_weight_file_path) + diffusion_pipeline.fuse_lora(lora_scale=command_line_args.lora_scale) + + diffusion_pipeline = diffusion_pipeline.to(dtype=torch.float16) + logger.info("Saving file...") + + text_encoder_primary = diffusion_pipeline.text_encoder + text_encoder_secondary = diffusion_pipeline.text_encoder_2 + variational_autoencoder = diffusion_pipeline.vae + unet_network = diffusion_pipeline.unet + + del diffusion_pipeline + + state_dict = convert_diffusers_unet_state_dict_to_sdxl(unet_network.state_dict()) + with init_empty_weights(): + unet_network = sdxl_original_unet.SdxlUNet2DConditionModel() + + load_state_dict_on_device(unet_network, state_dict, device="cuda", dtype=torch.float16) + + save_stable_diffusion_checkpoint( + command_line_args.name, + text_encoder_primary, + text_encoder_secondary, + unet_network, + None, + None, + None, + variational_autoencoder, + None, + None, + torch.float16, + ) + + logger.info("...done saving") + +def main(): + command_line_args = parse_command_line_arguments() + try: + diffusion_pipeline = load_diffusion_pipeline(command_line_args) + convert_and_save_diffusion_model(diffusion_pipeline, command_line_args) + except Exception as error: + logger.error(f"An error occurred: {error}") + +if __name__ == "__main__": + main() From 7cc3045e4a1f2b3ff26489460d22692186762af4 Mon Sep 17 00:00:00 2001 From: Disty0 Date: Thu, 14 Dec 2023 12:37:22 +0300 Subject: [PATCH 08/13] IPEX update to Torch 2.1 and bundle in MKL & DPCPP --- gui.sh | 10 ++-------- requirements_linux_ipex.txt | 5 +++-- 2 files changed, 5 insertions(+), 10 deletions(-) diff --git a/gui.sh b/gui.sh index a2ce52a45..da7d4cdf2 100755 --- a/gui.sh +++ b/gui.sh @@ -72,14 +72,8 @@ fi #Set OneAPI if it's not set by the user if [[ "$@" == *"--use-ipex"* ]] then - echo "Setting OneAPI environment" - if [ ! -x "$(command -v sycl-ls)" ] - then - if [[ -z "$ONEAPI_ROOT" ]] - then - ONEAPI_ROOT=/opt/intel/oneapi - fi - source $ONEAPI_ROOT/setvars.sh + if [ -d "$SCRIPT_DIR/venv" ]; then + export LD_LIBRARY_PATH=$(realpath "$SCRIPT_DIR/venv")/lib/:$LD_LIBRARY_PATH fi export NEOReadDebugKeys=1 export ClDeviceGlobalMemSizeAvailablePercent=100 diff --git a/requirements_linux_ipex.txt b/requirements_linux_ipex.txt index 20e9ed8bb..d461c9b76 100644 --- a/requirements_linux_ipex.txt +++ b/requirements_linux_ipex.txt @@ -1,3 +1,4 @@ -torch==2.0.1a0+cxx11.abi torchvision==0.15.2a0+cxx11.abi intel_extension_for_pytorch==2.0.110+xpu --extra-index-url https://pytorch-extension.intel.com/release-whl/stable/xpu/us/ -tensorboard==2.14.1 tensorflow==2.14.0 intel-extension-for-tensorflow[gpu] +torch==2.1.0a0+cxx11.abi torchvision==0.16.0a0+cxx11.abi intel-extension-for-pytorch==2.1.10+xpu --extra-index-url https://pytorch-extension.intel.com/release-whl/stable/xpu/us/ +tensorboard==2.14.1 tensorflow==2.14.0 intel-extension-for-tensorflow[xpu]==2.14.0.1 +mkl==2024.0.0 mkl-dpcpp==2024.0.0 -r requirements.txt From 96f113b8ec3809e339b772d874712b3ace5129f9 Mon Sep 17 00:00:00 2001 From: bmaltais Date: Mon, 18 Dec 2023 19:41:53 -0500 Subject: [PATCH 09/13] Update lr_scheduler_args placeholder --- library/class_basic_training.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/class_basic_training.py b/library/class_basic_training.py index e0bb2f1ef..5aaa52d81 100644 --- a/library/class_basic_training.py +++ b/library/class_basic_training.py @@ -123,7 +123,7 @@ def __init__( ) self.lr_scheduler_args = gr.Textbox( label="LR scheduler extra arguments", - placeholder='(Optional) eg: "lr_end=5e-5"', + placeholder='(Optional) eg: "milestones=[1,10,30,50]" "gamma=0.1"', ) self.optimizer_args = gr.Textbox( label="Optimizer extra arguments", From 6dc1928994fa73f0770518806a52b036bbf98035 Mon Sep 17 00:00:00 2001 From: Lucas Freire Sangoi <125471877+DevArqSangoi@users.noreply.github.com> Date: Tue, 19 Dec 2023 11:53:06 -0300 Subject: [PATCH 10/13] Update lpw_stable_diffusion.py Workaround for this: https://github.com/bmaltais/kohya_ss/issues/1780 --- library/lpw_stable_diffusion.py | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/library/lpw_stable_diffusion.py b/library/lpw_stable_diffusion.py index 9dce91a76..4f9408352 100644 --- a/library/lpw_stable_diffusion.py +++ b/library/lpw_stable_diffusion.py @@ -9,7 +9,7 @@ import PIL.Image import torch from packaging import version -from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer +from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection import diffusers from diffusers import SchedulerMixin, StableDiffusionPipeline @@ -516,12 +516,13 @@ def __init__( tokenizer: CLIPTokenizer, unet: UNet2DConditionModel, scheduler: SchedulerMixin, - # clip_skip: int, safety_checker: StableDiffusionSafetyChecker, feature_extractor: CLIPFeatureExtractor, + image_encoder: CLIPVisionModelWithProjection = None, # Incluindo o image_encoder requires_safety_checker: bool = True, clip_skip: int = 1, ): + self._clip_skip_internal = clip_skip super().__init__( vae=vae, text_encoder=text_encoder, @@ -530,11 +531,25 @@ def __init__( scheduler=scheduler, safety_checker=safety_checker, feature_extractor=feature_extractor, + image_encoder=image_encoder, requires_safety_checker=requires_safety_checker, ) - self.clip_skip = clip_skip self.__init__additional__() + @property + def clip_skip(self): + return self._clip_skip_internal + + @clip_skip.setter + def clip_skip(self, value): + self._clip_skip_internal = value + + def __setattr__(self, name: str, value): + if name == "clip_skip": + object.__setattr__(self, "_clip_skip_internal", value) + else: + super().__setattr__(name, value) + # else: # def __init__( # self, From 6c5ed5caa503eac20f733147b5905c437580b4ba Mon Sep 17 00:00:00 2001 From: bmaltais Date: Tue, 19 Dec 2023 19:01:31 -0500 Subject: [PATCH 11/13] Update lycoris module version --- library/lpw_stable_diffusion_orig.py | 1254 ++++++++++++++++++++++++++ requirements.txt | 2 +- 2 files changed, 1255 insertions(+), 1 deletion(-) create mode 100644 library/lpw_stable_diffusion_orig.py diff --git a/library/lpw_stable_diffusion_orig.py b/library/lpw_stable_diffusion_orig.py new file mode 100644 index 000000000..9dce91a76 --- /dev/null +++ b/library/lpw_stable_diffusion_orig.py @@ -0,0 +1,1254 @@ +# copy from https://github.com/huggingface/diffusers/blob/main/examples/community/lpw_stable_diffusion.py +# and modify to support SD2.x + +import inspect +import re +from typing import Callable, List, Optional, Union + +import numpy as np +import PIL.Image +import torch +from packaging import version +from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer + +import diffusers +from diffusers import SchedulerMixin, StableDiffusionPipeline +from diffusers.models import AutoencoderKL, UNet2DConditionModel +from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput, StableDiffusionSafetyChecker +from diffusers.utils import logging + + +try: + from diffusers.utils import PIL_INTERPOLATION +except ImportError: + if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("9.1.0"): + PIL_INTERPOLATION = { + "linear": PIL.Image.Resampling.BILINEAR, + "bilinear": PIL.Image.Resampling.BILINEAR, + "bicubic": PIL.Image.Resampling.BICUBIC, + "lanczos": PIL.Image.Resampling.LANCZOS, + "nearest": PIL.Image.Resampling.NEAREST, + } + else: + PIL_INTERPOLATION = { + "linear": PIL.Image.LINEAR, + "bilinear": PIL.Image.BILINEAR, + "bicubic": PIL.Image.BICUBIC, + "lanczos": PIL.Image.LANCZOS, + "nearest": PIL.Image.NEAREST, + } +# ------------------------------------------------------------------------------ + +logger = logging.get_logger(__name__) # pylint: disable=invalid-name + +re_attention = re.compile( + r""" +\\\(| +\\\)| +\\\[| +\\]| +\\\\| +\\| +\(| +\[| +:([+-]?[.\d]+)\)| +\)| +]| +[^\\()\[\]:]+| +: +""", + re.X, +) + + +def parse_prompt_attention(text): + """ + Parses a string with attention tokens and returns a list of pairs: text and its associated weight. + Accepted tokens are: + (abc) - increases attention to abc by a multiplier of 1.1 + (abc:3.12) - increases attention to abc by a multiplier of 3.12 + [abc] - decreases attention to abc by a multiplier of 1.1 + \( - literal character '(' + \[ - literal character '[' + \) - literal character ')' + \] - literal character ']' + \\ - literal character '\' + anything else - just text + >>> parse_prompt_attention('normal text') + [['normal text', 1.0]] + >>> parse_prompt_attention('an (important) word') + [['an ', 1.0], ['important', 1.1], [' word', 1.0]] + >>> parse_prompt_attention('(unbalanced') + [['unbalanced', 1.1]] + >>> parse_prompt_attention('\(literal\]') + [['(literal]', 1.0]] + >>> parse_prompt_attention('(unnecessary)(parens)') + [['unnecessaryparens', 1.1]] + >>> parse_prompt_attention('a (((house:1.3)) [on] a (hill:0.5), sun, (((sky))).') + [['a ', 1.0], + ['house', 1.5730000000000004], + [' ', 1.1], + ['on', 1.0], + [' a ', 1.1], + ['hill', 0.55], + [', sun, ', 1.1], + ['sky', 1.4641000000000006], + ['.', 1.1]] + """ + + res = [] + round_brackets = [] + square_brackets = [] + + round_bracket_multiplier = 1.1 + square_bracket_multiplier = 1 / 1.1 + + def multiply_range(start_position, multiplier): + for p in range(start_position, len(res)): + res[p][1] *= multiplier + + for m in re_attention.finditer(text): + text = m.group(0) + weight = m.group(1) + + if text.startswith("\\"): + res.append([text[1:], 1.0]) + elif text == "(": + round_brackets.append(len(res)) + elif text == "[": + square_brackets.append(len(res)) + elif weight is not None and len(round_brackets) > 0: + multiply_range(round_brackets.pop(), float(weight)) + elif text == ")" and len(round_brackets) > 0: + multiply_range(round_brackets.pop(), round_bracket_multiplier) + elif text == "]" and len(square_brackets) > 0: + multiply_range(square_brackets.pop(), square_bracket_multiplier) + else: + res.append([text, 1.0]) + + for pos in round_brackets: + multiply_range(pos, round_bracket_multiplier) + + for pos in square_brackets: + multiply_range(pos, square_bracket_multiplier) + + if len(res) == 0: + res = [["", 1.0]] + + # merge runs of identical weights + i = 0 + while i + 1 < len(res): + if res[i][1] == res[i + 1][1]: + res[i][0] += res[i + 1][0] + res.pop(i + 1) + else: + i += 1 + + return res + + +def get_prompts_with_weights(pipe: StableDiffusionPipeline, prompt: List[str], max_length: int): + r""" + Tokenize a list of prompts and return its tokens with weights of each token. + + No padding, starting or ending token is included. + """ + tokens = [] + weights = [] + truncated = False + for text in prompt: + texts_and_weights = parse_prompt_attention(text) + text_token = [] + text_weight = [] + for word, weight in texts_and_weights: + # tokenize and discard the starting and the ending token + token = pipe.tokenizer(word).input_ids[1:-1] + text_token += token + # copy the weight by length of token + text_weight += [weight] * len(token) + # stop if the text is too long (longer than truncation limit) + if len(text_token) > max_length: + truncated = True + break + # truncate + if len(text_token) > max_length: + truncated = True + text_token = text_token[:max_length] + text_weight = text_weight[:max_length] + tokens.append(text_token) + weights.append(text_weight) + if truncated: + logger.warning("Prompt was truncated. Try to shorten the prompt or increase max_embeddings_multiples") + return tokens, weights + + +def pad_tokens_and_weights(tokens, weights, max_length, bos, eos, no_boseos_middle=True, chunk_length=77): + r""" + Pad the tokens (with starting and ending tokens) and weights (with 1.0) to max_length. + """ + max_embeddings_multiples = (max_length - 2) // (chunk_length - 2) + weights_length = max_length if no_boseos_middle else max_embeddings_multiples * chunk_length + for i in range(len(tokens)): + tokens[i] = [bos] + tokens[i] + [eos] * (max_length - 1 - len(tokens[i])) + if no_boseos_middle: + weights[i] = [1.0] + weights[i] + [1.0] * (max_length - 1 - len(weights[i])) + else: + w = [] + if len(weights[i]) == 0: + w = [1.0] * weights_length + else: + for j in range(max_embeddings_multiples): + w.append(1.0) # weight for starting token in this chunk + w += weights[i][j * (chunk_length - 2) : min(len(weights[i]), (j + 1) * (chunk_length - 2))] + w.append(1.0) # weight for ending token in this chunk + w += [1.0] * (weights_length - len(w)) + weights[i] = w[:] + + return tokens, weights + + +def get_unweighted_text_embeddings( + pipe: StableDiffusionPipeline, + text_input: torch.Tensor, + chunk_length: int, + clip_skip: int, + eos: int, + pad: int, + no_boseos_middle: Optional[bool] = True, +): + """ + When the length of tokens is a multiple of the capacity of the text encoder, + it should be split into chunks and sent to the text encoder individually. + """ + max_embeddings_multiples = (text_input.shape[1] - 2) // (chunk_length - 2) + if max_embeddings_multiples > 1: + text_embeddings = [] + for i in range(max_embeddings_multiples): + # extract the i-th chunk + text_input_chunk = text_input[:, i * (chunk_length - 2) : (i + 1) * (chunk_length - 2) + 2].clone() + + # cover the head and the tail by the starting and the ending tokens + text_input_chunk[:, 0] = text_input[0, 0] + if pad == eos: # v1 + text_input_chunk[:, -1] = text_input[0, -1] + else: # v2 + for j in range(len(text_input_chunk)): + if text_input_chunk[j, -1] != eos and text_input_chunk[j, -1] != pad: # 最後に普通の文字がある + text_input_chunk[j, -1] = eos + if text_input_chunk[j, 1] == pad: # BOSだけであとはPAD + text_input_chunk[j, 1] = eos + + if clip_skip is None or clip_skip == 1: + text_embedding = pipe.text_encoder(text_input_chunk)[0] + else: + enc_out = pipe.text_encoder(text_input_chunk, output_hidden_states=True, return_dict=True) + text_embedding = enc_out["hidden_states"][-clip_skip] + text_embedding = pipe.text_encoder.text_model.final_layer_norm(text_embedding) + + if no_boseos_middle: + if i == 0: + # discard the ending token + text_embedding = text_embedding[:, :-1] + elif i == max_embeddings_multiples - 1: + # discard the starting token + text_embedding = text_embedding[:, 1:] + else: + # discard both starting and ending tokens + text_embedding = text_embedding[:, 1:-1] + + text_embeddings.append(text_embedding) + text_embeddings = torch.concat(text_embeddings, axis=1) + else: + if clip_skip is None or clip_skip == 1: + text_embeddings = pipe.text_encoder(text_input)[0] + else: + enc_out = pipe.text_encoder(text_input, output_hidden_states=True, return_dict=True) + text_embeddings = enc_out["hidden_states"][-clip_skip] + text_embeddings = pipe.text_encoder.text_model.final_layer_norm(text_embeddings) + return text_embeddings + + +def get_weighted_text_embeddings( + pipe: StableDiffusionPipeline, + prompt: Union[str, List[str]], + uncond_prompt: Optional[Union[str, List[str]]] = None, + max_embeddings_multiples: Optional[int] = 3, + no_boseos_middle: Optional[bool] = False, + skip_parsing: Optional[bool] = False, + skip_weighting: Optional[bool] = False, + clip_skip=None, +): + r""" + Prompts can be assigned with local weights using brackets. For example, + prompt 'A (very beautiful) masterpiece' highlights the words 'very beautiful', + and the embedding tokens corresponding to the words get multiplied by a constant, 1.1. + + Also, to regularize of the embedding, the weighted embedding would be scaled to preserve the original mean. + + Args: + pipe (`StableDiffusionPipeline`): + Pipe to provide access to the tokenizer and the text encoder. + prompt (`str` or `List[str]`): + The prompt or prompts to guide the image generation. + uncond_prompt (`str` or `List[str]`): + The unconditional prompt or prompts for guide the image generation. If unconditional prompt + is provided, the embeddings of prompt and uncond_prompt are concatenated. + max_embeddings_multiples (`int`, *optional*, defaults to `3`): + The max multiple length of prompt embeddings compared to the max output length of text encoder. + no_boseos_middle (`bool`, *optional*, defaults to `False`): + If the length of text token is multiples of the capacity of text encoder, whether reserve the starting and + ending token in each of the chunk in the middle. + skip_parsing (`bool`, *optional*, defaults to `False`): + Skip the parsing of brackets. + skip_weighting (`bool`, *optional*, defaults to `False`): + Skip the weighting. When the parsing is skipped, it is forced True. + """ + max_length = (pipe.tokenizer.model_max_length - 2) * max_embeddings_multiples + 2 + if isinstance(prompt, str): + prompt = [prompt] + + if not skip_parsing: + prompt_tokens, prompt_weights = get_prompts_with_weights(pipe, prompt, max_length - 2) + if uncond_prompt is not None: + if isinstance(uncond_prompt, str): + uncond_prompt = [uncond_prompt] + uncond_tokens, uncond_weights = get_prompts_with_weights(pipe, uncond_prompt, max_length - 2) + else: + prompt_tokens = [token[1:-1] for token in pipe.tokenizer(prompt, max_length=max_length, truncation=True).input_ids] + prompt_weights = [[1.0] * len(token) for token in prompt_tokens] + if uncond_prompt is not None: + if isinstance(uncond_prompt, str): + uncond_prompt = [uncond_prompt] + uncond_tokens = [ + token[1:-1] for token in pipe.tokenizer(uncond_prompt, max_length=max_length, truncation=True).input_ids + ] + uncond_weights = [[1.0] * len(token) for token in uncond_tokens] + + # round up the longest length of tokens to a multiple of (model_max_length - 2) + max_length = max([len(token) for token in prompt_tokens]) + if uncond_prompt is not None: + max_length = max(max_length, max([len(token) for token in uncond_tokens])) + + max_embeddings_multiples = min( + max_embeddings_multiples, + (max_length - 1) // (pipe.tokenizer.model_max_length - 2) + 1, + ) + max_embeddings_multiples = max(1, max_embeddings_multiples) + max_length = (pipe.tokenizer.model_max_length - 2) * max_embeddings_multiples + 2 + + # pad the length of tokens and weights + bos = pipe.tokenizer.bos_token_id + eos = pipe.tokenizer.eos_token_id + pad = pipe.tokenizer.pad_token_id + prompt_tokens, prompt_weights = pad_tokens_and_weights( + prompt_tokens, + prompt_weights, + max_length, + bos, + eos, + no_boseos_middle=no_boseos_middle, + chunk_length=pipe.tokenizer.model_max_length, + ) + prompt_tokens = torch.tensor(prompt_tokens, dtype=torch.long, device=pipe.device) + if uncond_prompt is not None: + uncond_tokens, uncond_weights = pad_tokens_and_weights( + uncond_tokens, + uncond_weights, + max_length, + bos, + eos, + no_boseos_middle=no_boseos_middle, + chunk_length=pipe.tokenizer.model_max_length, + ) + uncond_tokens = torch.tensor(uncond_tokens, dtype=torch.long, device=pipe.device) + + # get the embeddings + text_embeddings = get_unweighted_text_embeddings( + pipe, + prompt_tokens, + pipe.tokenizer.model_max_length, + clip_skip, + eos, + pad, + no_boseos_middle=no_boseos_middle, + ) + prompt_weights = torch.tensor(prompt_weights, dtype=text_embeddings.dtype, device=pipe.device) + if uncond_prompt is not None: + uncond_embeddings = get_unweighted_text_embeddings( + pipe, + uncond_tokens, + pipe.tokenizer.model_max_length, + clip_skip, + eos, + pad, + no_boseos_middle=no_boseos_middle, + ) + uncond_weights = torch.tensor(uncond_weights, dtype=uncond_embeddings.dtype, device=pipe.device) + + # assign weights to the prompts and normalize in the sense of mean + # TODO: should we normalize by chunk or in a whole (current implementation)? + if (not skip_parsing) and (not skip_weighting): + previous_mean = text_embeddings.float().mean(axis=[-2, -1]).to(text_embeddings.dtype) + text_embeddings *= prompt_weights.unsqueeze(-1) + current_mean = text_embeddings.float().mean(axis=[-2, -1]).to(text_embeddings.dtype) + text_embeddings *= (previous_mean / current_mean).unsqueeze(-1).unsqueeze(-1) + if uncond_prompt is not None: + previous_mean = uncond_embeddings.float().mean(axis=[-2, -1]).to(uncond_embeddings.dtype) + uncond_embeddings *= uncond_weights.unsqueeze(-1) + current_mean = uncond_embeddings.float().mean(axis=[-2, -1]).to(uncond_embeddings.dtype) + uncond_embeddings *= (previous_mean / current_mean).unsqueeze(-1).unsqueeze(-1) + + if uncond_prompt is not None: + return text_embeddings, uncond_embeddings + return text_embeddings, None + + +def preprocess_image(image): + w, h = image.size + w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32 + image = image.resize((w, h), resample=PIL_INTERPOLATION["lanczos"]) + image = np.array(image).astype(np.float32) / 255.0 + image = image[None].transpose(0, 3, 1, 2) + image = torch.from_numpy(image) + return 2.0 * image - 1.0 + + +def preprocess_mask(mask, scale_factor=8): + mask = mask.convert("L") + w, h = mask.size + w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32 + mask = mask.resize((w // scale_factor, h // scale_factor), resample=PIL_INTERPOLATION["nearest"]) + mask = np.array(mask).astype(np.float32) / 255.0 + mask = np.tile(mask, (4, 1, 1)) + mask = mask[None].transpose(0, 1, 2, 3) # what does this step do? + mask = 1 - mask # repaint white, keep black + mask = torch.from_numpy(mask) + return mask + + +def prepare_controlnet_image( + image: PIL.Image.Image, + width: int, + height: int, + batch_size: int, + num_images_per_prompt: int, + device: torch.device, + dtype: torch.dtype, + do_classifier_free_guidance: bool = False, + guess_mode: bool = False, +): + if not isinstance(image, torch.Tensor): + if isinstance(image, PIL.Image.Image): + image = [image] + + if isinstance(image[0], PIL.Image.Image): + images = [] + + for image_ in image: + image_ = image_.convert("RGB") + image_ = image_.resize((width, height), resample=PIL_INTERPOLATION["lanczos"]) + image_ = np.array(image_) + image_ = image_[None, :] + images.append(image_) + + image = images + + image = np.concatenate(image, axis=0) + image = np.array(image).astype(np.float32) / 255.0 + image = image.transpose(0, 3, 1, 2) + image = torch.from_numpy(image) + elif isinstance(image[0], torch.Tensor): + image = torch.cat(image, dim=0) + + image_batch_size = image.shape[0] + + if image_batch_size == 1: + repeat_by = batch_size + else: + # image batch size is the same as prompt batch size + repeat_by = num_images_per_prompt + + image = image.repeat_interleave(repeat_by, dim=0) + + image = image.to(device=device, dtype=dtype) + + if do_classifier_free_guidance and not guess_mode: + image = torch.cat([image] * 2) + + return image + + +class StableDiffusionLongPromptWeightingPipeline(StableDiffusionPipeline): + r""" + Pipeline for text-to-image generation using Stable Diffusion without tokens length limit, and support parsing + weighting in prompt. + + This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the + library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.) + + Args: + vae ([`AutoencoderKL`]): + Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations. + text_encoder ([`CLIPTextModel`]): + Frozen text-encoder. Stable Diffusion uses the text portion of + [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically + the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant. + tokenizer (`CLIPTokenizer`): + Tokenizer of class + [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer). + unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents. + scheduler ([`SchedulerMixin`]): + A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of + [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`]. + safety_checker ([`StableDiffusionSafetyChecker`]): + Classification module that estimates whether generated images could be considered offensive or harmful. + Please, refer to the [model card](https://huggingface.co/CompVis/stable-diffusion-v1-4) for details. + feature_extractor ([`CLIPFeatureExtractor`]): + Model that extracts features from generated images to be used as inputs for the `safety_checker`. + """ + + # if version.parse(version.parse(diffusers.__version__).base_version) >= version.parse("0.9.0"): + + def __init__( + self, + vae: AutoencoderKL, + text_encoder: CLIPTextModel, + tokenizer: CLIPTokenizer, + unet: UNet2DConditionModel, + scheduler: SchedulerMixin, + # clip_skip: int, + safety_checker: StableDiffusionSafetyChecker, + feature_extractor: CLIPFeatureExtractor, + requires_safety_checker: bool = True, + clip_skip: int = 1, + ): + super().__init__( + vae=vae, + text_encoder=text_encoder, + tokenizer=tokenizer, + unet=unet, + scheduler=scheduler, + safety_checker=safety_checker, + feature_extractor=feature_extractor, + requires_safety_checker=requires_safety_checker, + ) + self.clip_skip = clip_skip + self.__init__additional__() + + # else: + # def __init__( + # self, + # vae: AutoencoderKL, + # text_encoder: CLIPTextModel, + # tokenizer: CLIPTokenizer, + # unet: UNet2DConditionModel, + # scheduler: SchedulerMixin, + # safety_checker: StableDiffusionSafetyChecker, + # feature_extractor: CLIPFeatureExtractor, + # ): + # super().__init__( + # vae=vae, + # text_encoder=text_encoder, + # tokenizer=tokenizer, + # unet=unet, + # scheduler=scheduler, + # safety_checker=safety_checker, + # feature_extractor=feature_extractor, + # ) + # self.__init__additional__() + + def __init__additional__(self): + if not hasattr(self, "vae_scale_factor"): + setattr(self, "vae_scale_factor", 2 ** (len(self.vae.config.block_out_channels) - 1)) + + @property + def _execution_device(self): + r""" + Returns the device on which the pipeline's models will be executed. After calling + `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module + hooks. + """ + if self.device != torch.device("meta") or not hasattr(self.unet, "_hf_hook"): + return self.device + for module in self.unet.modules(): + if ( + hasattr(module, "_hf_hook") + and hasattr(module._hf_hook, "execution_device") + and module._hf_hook.execution_device is not None + ): + return torch.device(module._hf_hook.execution_device) + return self.device + + def _encode_prompt( + self, + prompt, + device, + num_images_per_prompt, + do_classifier_free_guidance, + negative_prompt, + max_embeddings_multiples, + ): + r""" + Encodes the prompt into text encoder hidden states. + + Args: + prompt (`str` or `list(int)`): + prompt to be encoded + device: (`torch.device`): + torch device + num_images_per_prompt (`int`): + number of images that should be generated per prompt + do_classifier_free_guidance (`bool`): + whether to use classifier free guidance or not + negative_prompt (`str` or `List[str]`): + The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored + if `guidance_scale` is less than `1`). + max_embeddings_multiples (`int`, *optional*, defaults to `3`): + The max multiple length of prompt embeddings compared to the max output length of text encoder. + """ + batch_size = len(prompt) if isinstance(prompt, list) else 1 + + if negative_prompt is None: + negative_prompt = [""] * batch_size + elif isinstance(negative_prompt, str): + negative_prompt = [negative_prompt] * batch_size + if batch_size != len(negative_prompt): + raise ValueError( + f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:" + f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" + " the batch size of `prompt`." + ) + + text_embeddings, uncond_embeddings = get_weighted_text_embeddings( + pipe=self, + prompt=prompt, + uncond_prompt=negative_prompt if do_classifier_free_guidance else None, + max_embeddings_multiples=max_embeddings_multiples, + clip_skip=self.clip_skip, + ) + bs_embed, seq_len, _ = text_embeddings.shape + text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1) + text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1) + + if do_classifier_free_guidance: + bs_embed, seq_len, _ = uncond_embeddings.shape + uncond_embeddings = uncond_embeddings.repeat(1, num_images_per_prompt, 1) + uncond_embeddings = uncond_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1) + text_embeddings = torch.cat([uncond_embeddings, text_embeddings]) + + return text_embeddings + + def check_inputs(self, prompt, height, width, strength, callback_steps): + if not isinstance(prompt, str) and not isinstance(prompt, list): + raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}") + + if strength < 0 or strength > 1: + raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}") + + if height % 8 != 0 or width % 8 != 0: + print(height, width) + raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.") + + if (callback_steps is None) or ( + callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0) + ): + raise ValueError( + f"`callback_steps` has to be a positive integer but is {callback_steps} of type" f" {type(callback_steps)}." + ) + + def get_timesteps(self, num_inference_steps, strength, device, is_text2img): + if is_text2img: + return self.scheduler.timesteps.to(device), num_inference_steps + else: + # get the original timestep using init_timestep + offset = self.scheduler.config.get("steps_offset", 0) + init_timestep = int(num_inference_steps * strength) + offset + init_timestep = min(init_timestep, num_inference_steps) + + t_start = max(num_inference_steps - init_timestep + offset, 0) + timesteps = self.scheduler.timesteps[t_start:].to(device) + return timesteps, num_inference_steps - t_start + + def run_safety_checker(self, image, device, dtype): + if self.safety_checker is not None: + safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(device) + image, has_nsfw_concept = self.safety_checker(images=image, clip_input=safety_checker_input.pixel_values.to(dtype)) + else: + has_nsfw_concept = None + return image, has_nsfw_concept + + def decode_latents(self, latents): + latents = 1 / 0.18215 * latents + image = self.vae.decode(latents).sample + image = (image / 2 + 0.5).clamp(0, 1) + # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 + image = image.cpu().permute(0, 2, 3, 1).float().numpy() + return image + + def prepare_extra_step_kwargs(self, generator, eta): + # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature + # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. + # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 + # and should be between [0, 1] + + accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys()) + extra_step_kwargs = {} + if accepts_eta: + extra_step_kwargs["eta"] = eta + + # check if the scheduler accepts generator + accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys()) + if accepts_generator: + extra_step_kwargs["generator"] = generator + return extra_step_kwargs + + def prepare_latents(self, image, timestep, batch_size, height, width, dtype, device, generator, latents=None): + if image is None: + shape = ( + batch_size, + self.unet.in_channels, + height // self.vae_scale_factor, + width // self.vae_scale_factor, + ) + + if latents is None: + if device.type == "mps": + # randn does not work reproducibly on mps + latents = torch.randn(shape, generator=generator, device="cpu", dtype=dtype).to(device) + else: + latents = torch.randn(shape, generator=generator, device=device, dtype=dtype) + else: + if latents.shape != shape: + raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}") + latents = latents.to(device) + + # scale the initial noise by the standard deviation required by the scheduler + latents = latents * self.scheduler.init_noise_sigma + return latents, None, None + else: + init_latent_dist = self.vae.encode(image).latent_dist + init_latents = init_latent_dist.sample(generator=generator) + init_latents = 0.18215 * init_latents + init_latents = torch.cat([init_latents] * batch_size, dim=0) + init_latents_orig = init_latents + shape = init_latents.shape + + # add noise to latents using the timesteps + if device.type == "mps": + noise = torch.randn(shape, generator=generator, device="cpu", dtype=dtype).to(device) + else: + noise = torch.randn(shape, generator=generator, device=device, dtype=dtype) + latents = self.scheduler.add_noise(init_latents, noise, timestep) + return latents, init_latents_orig, noise + + @torch.no_grad() + def __call__( + self, + prompt: Union[str, List[str]], + negative_prompt: Optional[Union[str, List[str]]] = None, + image: Union[torch.FloatTensor, PIL.Image.Image] = None, + mask_image: Union[torch.FloatTensor, PIL.Image.Image] = None, + height: int = 512, + width: int = 512, + num_inference_steps: int = 50, + guidance_scale: float = 7.5, + strength: float = 0.8, + num_images_per_prompt: Optional[int] = 1, + eta: float = 0.0, + generator: Optional[torch.Generator] = None, + latents: Optional[torch.FloatTensor] = None, + max_embeddings_multiples: Optional[int] = 3, + output_type: Optional[str] = "pil", + return_dict: bool = True, + controlnet=None, + controlnet_image=None, + callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None, + is_cancelled_callback: Optional[Callable[[], bool]] = None, + callback_steps: int = 1, + ): + r""" + Function invoked when calling the pipeline for generation. + + Args: + prompt (`str` or `List[str]`): + The prompt or prompts to guide the image generation. + negative_prompt (`str` or `List[str]`, *optional*): + The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored + if `guidance_scale` is less than `1`). + image (`torch.FloatTensor` or `PIL.Image.Image`): + `Image`, or tensor representing an image batch, that will be used as the starting point for the + process. + mask_image (`torch.FloatTensor` or `PIL.Image.Image`): + `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be + replaced by noise and therefore repainted, while black pixels will be preserved. If `mask_image` is a + PIL image, it will be converted to a single channel (luminance) before use. If it's a tensor, it should + contain one color channel (L) instead of 3, so the expected shape would be `(B, H, W, 1)`. + height (`int`, *optional*, defaults to 512): + The height in pixels of the generated image. + width (`int`, *optional*, defaults to 512): + The width in pixels of the generated image. + num_inference_steps (`int`, *optional*, defaults to 50): + The number of denoising steps. More denoising steps usually lead to a higher quality image at the + expense of slower inference. + guidance_scale (`float`, *optional*, defaults to 7.5): + Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598). + `guidance_scale` is defined as `w` of equation 2. of [Imagen + Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale > + 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, + usually at the expense of lower image quality. + strength (`float`, *optional*, defaults to 0.8): + Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1. + `image` will be used as a starting point, adding more noise to it the larger the `strength`. The + number of denoising steps depends on the amount of noise initially added. When `strength` is 1, added + noise will be maximum and the denoising process will run for the full number of iterations specified in + `num_inference_steps`. A value of 1, therefore, essentially ignores `image`. + num_images_per_prompt (`int`, *optional*, defaults to 1): + The number of images to generate per prompt. + eta (`float`, *optional*, defaults to 0.0): + Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to + [`schedulers.DDIMScheduler`], will be ignored for others. + generator (`torch.Generator`, *optional*): + A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation + deterministic. + latents (`torch.FloatTensor`, *optional*): + Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image + generation. Can be used to tweak the same generation with different prompts. If not provided, a latents + tensor will ge generated by sampling using the supplied random `generator`. + max_embeddings_multiples (`int`, *optional*, defaults to `3`): + The max multiple length of prompt embeddings compared to the max output length of text encoder. + output_type (`str`, *optional*, defaults to `"pil"`): + The output format of the generate image. Choose between + [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`. + return_dict (`bool`, *optional*, defaults to `True`): + Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a + plain tuple. + controlnet (`diffusers.ControlNetModel`, *optional*): + A controlnet model to be used for the inference. If not provided, controlnet will be disabled. + controlnet_image (`torch.FloatTensor` or `PIL.Image.Image`, *optional*): + `Image`, or tensor representing an image batch, to be used as the starting point for the controlnet + inference. + callback (`Callable`, *optional*): + A function that will be called every `callback_steps` steps during inference. The function will be + called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`. + is_cancelled_callback (`Callable`, *optional*): + A function that will be called every `callback_steps` steps during inference. If the function returns + `True`, the inference will be cancelled. + callback_steps (`int`, *optional*, defaults to 1): + The frequency at which the `callback` function will be called. If not specified, the callback will be + called at every step. + + Returns: + `None` if cancelled by `is_cancelled_callback`, + [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`: + [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple. + When returning a tuple, the first element is a list with the generated images, and the second element is a + list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work" + (nsfw) content, according to the `safety_checker`. + """ + if controlnet is not None and controlnet_image is None: + raise ValueError("controlnet_image must be provided if controlnet is not None.") + + # 0. Default height and width to unet + height = height or self.unet.config.sample_size * self.vae_scale_factor + width = width or self.unet.config.sample_size * self.vae_scale_factor + + # 1. Check inputs. Raise error if not correct + self.check_inputs(prompt, height, width, strength, callback_steps) + + # 2. Define call parameters + batch_size = 1 if isinstance(prompt, str) else len(prompt) + device = self._execution_device + # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) + # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` + # corresponds to doing no classifier free guidance. + do_classifier_free_guidance = guidance_scale > 1.0 + + # 3. Encode input prompt + text_embeddings = self._encode_prompt( + prompt, + device, + num_images_per_prompt, + do_classifier_free_guidance, + negative_prompt, + max_embeddings_multiples, + ) + dtype = text_embeddings.dtype + + # 4. Preprocess image and mask + if isinstance(image, PIL.Image.Image): + image = preprocess_image(image) + if image is not None: + image = image.to(device=self.device, dtype=dtype) + if isinstance(mask_image, PIL.Image.Image): + mask_image = preprocess_mask(mask_image, self.vae_scale_factor) + if mask_image is not None: + mask = mask_image.to(device=self.device, dtype=dtype) + mask = torch.cat([mask] * batch_size * num_images_per_prompt) + else: + mask = None + + if controlnet_image is not None: + controlnet_image = prepare_controlnet_image( + controlnet_image, width, height, batch_size, 1, self.device, controlnet.dtype, do_classifier_free_guidance, False + ) + + # 5. set timesteps + self.scheduler.set_timesteps(num_inference_steps, device=device) + timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device, image is None) + latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt) + + # 6. Prepare latent variables + latents, init_latents_orig, noise = self.prepare_latents( + image, + latent_timestep, + batch_size * num_images_per_prompt, + height, + width, + dtype, + device, + generator, + latents, + ) + + # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline + extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta) + + # 8. Denoising loop + for i, t in enumerate(self.progress_bar(timesteps)): + # expand the latents if we are doing classifier free guidance + latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents + latent_model_input = self.scheduler.scale_model_input(latent_model_input, t) + + unet_additional_args = {} + if controlnet is not None: + down_block_res_samples, mid_block_res_sample = controlnet( + latent_model_input, + t, + encoder_hidden_states=text_embeddings, + controlnet_cond=controlnet_image, + conditioning_scale=1.0, + guess_mode=False, + return_dict=False, + ) + unet_additional_args["down_block_additional_residuals"] = down_block_res_samples + unet_additional_args["mid_block_additional_residual"] = mid_block_res_sample + + # predict the noise residual + noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings, **unet_additional_args).sample + + # perform guidance + if do_classifier_free_guidance: + noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) + noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) + + # compute the previous noisy sample x_t -> x_t-1 + latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample + + if mask is not None: + # masking + init_latents_proper = self.scheduler.add_noise(init_latents_orig, noise, torch.tensor([t])) + latents = (init_latents_proper * mask) + (latents * (1 - mask)) + + # call the callback, if provided + if i % callback_steps == 0: + if callback is not None: + callback(i, t, latents) + if is_cancelled_callback is not None and is_cancelled_callback(): + return None + + return latents + + def latents_to_image(self, latents): + # 9. Post-processing + image = self.decode_latents(latents.to(self.vae.dtype)) + image = self.numpy_to_pil(image) + return image + + def text2img( + self, + prompt: Union[str, List[str]], + negative_prompt: Optional[Union[str, List[str]]] = None, + height: int = 512, + width: int = 512, + num_inference_steps: int = 50, + guidance_scale: float = 7.5, + num_images_per_prompt: Optional[int] = 1, + eta: float = 0.0, + generator: Optional[torch.Generator] = None, + latents: Optional[torch.FloatTensor] = None, + max_embeddings_multiples: Optional[int] = 3, + output_type: Optional[str] = "pil", + return_dict: bool = True, + callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None, + is_cancelled_callback: Optional[Callable[[], bool]] = None, + callback_steps: int = 1, + ): + r""" + Function for text-to-image generation. + Args: + prompt (`str` or `List[str]`): + The prompt or prompts to guide the image generation. + negative_prompt (`str` or `List[str]`, *optional*): + The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored + if `guidance_scale` is less than `1`). + height (`int`, *optional*, defaults to 512): + The height in pixels of the generated image. + width (`int`, *optional*, defaults to 512): + The width in pixels of the generated image. + num_inference_steps (`int`, *optional*, defaults to 50): + The number of denoising steps. More denoising steps usually lead to a higher quality image at the + expense of slower inference. + guidance_scale (`float`, *optional*, defaults to 7.5): + Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598). + `guidance_scale` is defined as `w` of equation 2. of [Imagen + Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale > + 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, + usually at the expense of lower image quality. + num_images_per_prompt (`int`, *optional*, defaults to 1): + The number of images to generate per prompt. + eta (`float`, *optional*, defaults to 0.0): + Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to + [`schedulers.DDIMScheduler`], will be ignored for others. + generator (`torch.Generator`, *optional*): + A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation + deterministic. + latents (`torch.FloatTensor`, *optional*): + Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image + generation. Can be used to tweak the same generation with different prompts. If not provided, a latents + tensor will ge generated by sampling using the supplied random `generator`. + max_embeddings_multiples (`int`, *optional*, defaults to `3`): + The max multiple length of prompt embeddings compared to the max output length of text encoder. + output_type (`str`, *optional*, defaults to `"pil"`): + The output format of the generate image. Choose between + [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`. + return_dict (`bool`, *optional*, defaults to `True`): + Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a + plain tuple. + callback (`Callable`, *optional*): + A function that will be called every `callback_steps` steps during inference. The function will be + called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`. + is_cancelled_callback (`Callable`, *optional*): + A function that will be called every `callback_steps` steps during inference. If the function returns + `True`, the inference will be cancelled. + callback_steps (`int`, *optional*, defaults to 1): + The frequency at which the `callback` function will be called. If not specified, the callback will be + called at every step. + Returns: + [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`: + [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple. + When returning a tuple, the first element is a list with the generated images, and the second element is a + list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work" + (nsfw) content, according to the `safety_checker`. + """ + return self.__call__( + prompt=prompt, + negative_prompt=negative_prompt, + height=height, + width=width, + num_inference_steps=num_inference_steps, + guidance_scale=guidance_scale, + num_images_per_prompt=num_images_per_prompt, + eta=eta, + generator=generator, + latents=latents, + max_embeddings_multiples=max_embeddings_multiples, + output_type=output_type, + return_dict=return_dict, + callback=callback, + is_cancelled_callback=is_cancelled_callback, + callback_steps=callback_steps, + ) + + def img2img( + self, + image: Union[torch.FloatTensor, PIL.Image.Image], + prompt: Union[str, List[str]], + negative_prompt: Optional[Union[str, List[str]]] = None, + strength: float = 0.8, + num_inference_steps: Optional[int] = 50, + guidance_scale: Optional[float] = 7.5, + num_images_per_prompt: Optional[int] = 1, + eta: Optional[float] = 0.0, + generator: Optional[torch.Generator] = None, + max_embeddings_multiples: Optional[int] = 3, + output_type: Optional[str] = "pil", + return_dict: bool = True, + callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None, + is_cancelled_callback: Optional[Callable[[], bool]] = None, + callback_steps: int = 1, + ): + r""" + Function for image-to-image generation. + Args: + image (`torch.FloatTensor` or `PIL.Image.Image`): + `Image`, or tensor representing an image batch, that will be used as the starting point for the + process. + prompt (`str` or `List[str]`): + The prompt or prompts to guide the image generation. + negative_prompt (`str` or `List[str]`, *optional*): + The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored + if `guidance_scale` is less than `1`). + strength (`float`, *optional*, defaults to 0.8): + Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1. + `image` will be used as a starting point, adding more noise to it the larger the `strength`. The + number of denoising steps depends on the amount of noise initially added. When `strength` is 1, added + noise will be maximum and the denoising process will run for the full number of iterations specified in + `num_inference_steps`. A value of 1, therefore, essentially ignores `image`. + num_inference_steps (`int`, *optional*, defaults to 50): + The number of denoising steps. More denoising steps usually lead to a higher quality image at the + expense of slower inference. This parameter will be modulated by `strength`. + guidance_scale (`float`, *optional*, defaults to 7.5): + Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598). + `guidance_scale` is defined as `w` of equation 2. of [Imagen + Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale > + 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, + usually at the expense of lower image quality. + num_images_per_prompt (`int`, *optional*, defaults to 1): + The number of images to generate per prompt. + eta (`float`, *optional*, defaults to 0.0): + Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to + [`schedulers.DDIMScheduler`], will be ignored for others. + generator (`torch.Generator`, *optional*): + A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation + deterministic. + max_embeddings_multiples (`int`, *optional*, defaults to `3`): + The max multiple length of prompt embeddings compared to the max output length of text encoder. + output_type (`str`, *optional*, defaults to `"pil"`): + The output format of the generate image. Choose between + [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`. + return_dict (`bool`, *optional*, defaults to `True`): + Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a + plain tuple. + callback (`Callable`, *optional*): + A function that will be called every `callback_steps` steps during inference. The function will be + called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`. + is_cancelled_callback (`Callable`, *optional*): + A function that will be called every `callback_steps` steps during inference. If the function returns + `True`, the inference will be cancelled. + callback_steps (`int`, *optional*, defaults to 1): + The frequency at which the `callback` function will be called. If not specified, the callback will be + called at every step. + Returns: + [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`: + [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple. + When returning a tuple, the first element is a list with the generated images, and the second element is a + list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work" + (nsfw) content, according to the `safety_checker`. + """ + return self.__call__( + prompt=prompt, + negative_prompt=negative_prompt, + image=image, + num_inference_steps=num_inference_steps, + guidance_scale=guidance_scale, + strength=strength, + num_images_per_prompt=num_images_per_prompt, + eta=eta, + generator=generator, + max_embeddings_multiples=max_embeddings_multiples, + output_type=output_type, + return_dict=return_dict, + callback=callback, + is_cancelled_callback=is_cancelled_callback, + callback_steps=callback_steps, + ) + + def inpaint( + self, + image: Union[torch.FloatTensor, PIL.Image.Image], + mask_image: Union[torch.FloatTensor, PIL.Image.Image], + prompt: Union[str, List[str]], + negative_prompt: Optional[Union[str, List[str]]] = None, + strength: float = 0.8, + num_inference_steps: Optional[int] = 50, + guidance_scale: Optional[float] = 7.5, + num_images_per_prompt: Optional[int] = 1, + eta: Optional[float] = 0.0, + generator: Optional[torch.Generator] = None, + max_embeddings_multiples: Optional[int] = 3, + output_type: Optional[str] = "pil", + return_dict: bool = True, + callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None, + is_cancelled_callback: Optional[Callable[[], bool]] = None, + callback_steps: int = 1, + ): + r""" + Function for inpaint. + Args: + image (`torch.FloatTensor` or `PIL.Image.Image`): + `Image`, or tensor representing an image batch, that will be used as the starting point for the + process. This is the image whose masked region will be inpainted. + mask_image (`torch.FloatTensor` or `PIL.Image.Image`): + `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be + replaced by noise and therefore repainted, while black pixels will be preserved. If `mask_image` is a + PIL image, it will be converted to a single channel (luminance) before use. If it's a tensor, it should + contain one color channel (L) instead of 3, so the expected shape would be `(B, H, W, 1)`. + prompt (`str` or `List[str]`): + The prompt or prompts to guide the image generation. + negative_prompt (`str` or `List[str]`, *optional*): + The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored + if `guidance_scale` is less than `1`). + strength (`float`, *optional*, defaults to 0.8): + Conceptually, indicates how much to inpaint the masked area. Must be between 0 and 1. When `strength` + is 1, the denoising process will be run on the masked area for the full number of iterations specified + in `num_inference_steps`. `image` will be used as a reference for the masked area, adding more + noise to that region the larger the `strength`. If `strength` is 0, no inpainting will occur. + num_inference_steps (`int`, *optional*, defaults to 50): + The reference number of denoising steps. More denoising steps usually lead to a higher quality image at + the expense of slower inference. This parameter will be modulated by `strength`, as explained above. + guidance_scale (`float`, *optional*, defaults to 7.5): + Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598). + `guidance_scale` is defined as `w` of equation 2. of [Imagen + Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale > + 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, + usually at the expense of lower image quality. + num_images_per_prompt (`int`, *optional*, defaults to 1): + The number of images to generate per prompt. + eta (`float`, *optional*, defaults to 0.0): + Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to + [`schedulers.DDIMScheduler`], will be ignored for others. + generator (`torch.Generator`, *optional*): + A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation + deterministic. + max_embeddings_multiples (`int`, *optional*, defaults to `3`): + The max multiple length of prompt embeddings compared to the max output length of text encoder. + output_type (`str`, *optional*, defaults to `"pil"`): + The output format of the generate image. Choose between + [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`. + return_dict (`bool`, *optional*, defaults to `True`): + Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a + plain tuple. + callback (`Callable`, *optional*): + A function that will be called every `callback_steps` steps during inference. The function will be + called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`. + is_cancelled_callback (`Callable`, *optional*): + A function that will be called every `callback_steps` steps during inference. If the function returns + `True`, the inference will be cancelled. + callback_steps (`int`, *optional*, defaults to 1): + The frequency at which the `callback` function will be called. If not specified, the callback will be + called at every step. + Returns: + [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`: + [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple. + When returning a tuple, the first element is a list with the generated images, and the second element is a + list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work" + (nsfw) content, according to the `safety_checker`. + """ + return self.__call__( + prompt=prompt, + negative_prompt=negative_prompt, + image=image, + mask_image=mask_image, + num_inference_steps=num_inference_steps, + guidance_scale=guidance_scale, + strength=strength, + num_images_per_prompt=num_images_per_prompt, + eta=eta, + generator=generator, + max_embeddings_multiples=max_embeddings_multiples, + output_type=output_type, + return_dict=return_dict, + callback=callback, + is_cancelled_callback=is_cancelled_callback, + callback_steps=callback_steps, + ) diff --git a/requirements.txt b/requirements.txt index c49917a40..5dc8a40ee 100644 --- a/requirements.txt +++ b/requirements.txt @@ -13,7 +13,7 @@ huggingface-hub==0.19.4 # for loading Diffusers' SDXL invisible-watermark==0.2.0 lion-pytorch==0.0.6 -lycoris_lora==2.0.0 +lycoris_lora==2.0.2 # for BLIP captioning # requests==2.28.2 # timm==0.6.12 From d87d7cafdf5f0386f30217064e0a5a5eabcbb47b Mon Sep 17 00:00:00 2001 From: bmaltais Date: Tue, 19 Dec 2023 19:05:29 -0500 Subject: [PATCH 12/13] Revert changing value --- lora_gui.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lora_gui.py b/lora_gui.py index baf34b4af..fcfc3303a 100644 --- a/lora_gui.py +++ b/lora_gui.py @@ -1505,7 +1505,7 @@ def update_LoRA_settings( "maximum": 100000 if LoRA_type in {"LyCORIS/LoHa", "LyCORIS/LoKr", "LyCORIS/Diag-OFT"} else 512, - "value": 512 if conv_dim > 512 else conv_dim, + "value": 512, # if conv_dim > 512 else conv_dim, }, }, "network_dim": { @@ -1514,7 +1514,7 @@ def update_LoRA_settings( "maximum": 100000 if LoRA_type in {"LyCORIS/LoHa", "LyCORIS/LoKr", "LyCORIS/Diag-OFT"} else 512, - "value": 512 if network_dim > 512 else network_dim, + "value": 512, # if network_dim > 512 else network_dim, }, }, "use_cp": { From ce74aac344861ec5f1362310b5c5edd743fe7451 Mon Sep 17 00:00:00 2001 From: bmaltais Date: Wed, 20 Dec 2023 19:05:46 -0500 Subject: [PATCH 13/13] Update readme --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 0751ca275..eeeadd974 100644 --- a/README.md +++ b/README.md @@ -651,11 +651,12 @@ masterpiece, best quality, 1boy, in business suit, standing at street, looking b ## Change History -* 2023/12/10 (v22.3.1) +* 2023/12/20 (v22.3.1) - Add goto button to manual caption utility - Add missing options for various LyCORIS training algorythms - Refactor how feilds are shown or hidden - Made max value for network and convolution rank 512 except for LyCORIS/LoKr. + * 2023/12/06 (v22.3.0) - Merge sd-scripts updates: - `finetune\tag_images_by_wd14_tagger.py` now supports the separator other than `,` with `--caption_separator` option. Thanks to KohakuBlueleaf! PR [#913](https://github.com/kohya-ss/sd-scripts/pull/913)