Skip to content

Commit e69d341

Browse files
authored
Merge pull request kohya-ss#1136 from kohya-ss/dev
v0.8.4
2 parents cd19df4 + a21218b commit e69d341

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

72 files changed

+6730
-1764
lines changed

README.md

Lines changed: 43 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,49 @@ ControlNet-LLLite, a novel method for ControlNet with SDXL, is added. See [docum
249249

250250
## Change History
251251

252+
### Feb 24, 2024 / 2024/2/24: v0.8.4
253+
254+
- The log output has been improved. PR [#905](https://github.com/kohya-ss/sd-scripts/pull/905) Thanks to shirayu!
255+
- The log is formatted by default. The `rich` library is required. Please see [Upgrade](#upgrade) and update the library.
256+
- If `rich` is not installed, the log output will be the same as before.
257+
- The following options are available in each training script:
258+
- `--console_log_simple` option can be used to switch to the previous log output.
259+
- `--console_log_level` option can be used to specify the log level. The default is `INFO`.
260+
- `--console_log_file` option can be used to output the log to a file. The default is `None` (output to the console).
261+
- The sample image generation during multi-GPU training is now done with multiple GPUs. PR [#1061](https://github.com/kohya-ss/sd-scripts/pull/1061) Thanks to DKnight54!
262+
- The support for mps devices is improved. PR [#1054](https://github.com/kohya-ss/sd-scripts/pull/1054) Thanks to akx! If mps device exists instead of CUDA, the mps device is used automatically.
263+
- The `--new_conv_rank` option to specify the new rank of Conv2d is added to `networks/resize_lora.py`. PR [#1102](https://github.com/kohya-ss/sd-scripts/pull/1102) Thanks to mgz-dev!
264+
- An option `--highvram` to disable the optimization for environments with little VRAM is added to the training scripts. If you specify it when there is enough VRAM, the operation will be faster.
265+
- Currently, only the cache part of latents is optimized.
266+
- The IPEX support is improved. PR [#1086](https://github.com/kohya-ss/sd-scripts/pull/1086) Thanks to Disty0!
267+
- Fixed a bug that `svd_merge_lora.py` crashes in some cases. PR [#1087](https://github.com/kohya-ss/sd-scripts/pull/1087) Thanks to mgz-dev!
268+
- DyLoRA is fixed to work with SDXL. PR [#1126](https://github.com/kohya-ss/sd-scripts/pull/1126) Thanks to tamlog06!
269+
- The common image generation script `gen_img.py` for SD 1/2 and SDXL is added. The basic functions are the same as the scripts for SD 1/2 and SDXL, but some new features are added.
270+
- External scripts to generate prompts can be supported. It can be called with `--from_module` option. (The documentation will be added later)
271+
- The normalization method after prompt weighting can be specified with `--emb_normalize_mode` option. `original` is the original method, `abs` is the normalization with the average of the absolute values, `none` is no normalization.
272+
- Gradual Latent Hires fix is added to each generation script. See [here](./docs/gen_img_README-ja.md#about-gradual-latent) for details.
273+
274+
- ログ出力が改善されました。 PR [#905](https://github.com/kohya-ss/sd-scripts/pull/905) shirayu 氏に感謝します。
275+
- デフォルトでログが成形されます。`rich` ライブラリが必要なため、[Upgrade](#upgrade) を参照し更新をお願いします。
276+
- `rich` がインストールされていない場合は、従来のログ出力になります。
277+
- 各学習スクリプトでは以下のオプションが有効です。
278+
- `--console_log_simple` オプションで従来のログ出力に切り替えられます。
279+
- `--console_log_level` でログレベルを指定できます。デフォルトは `INFO` です。
280+
- `--console_log_file` でログファイルを出力できます。デフォルトは `None`(コンソールに出力) です。
281+
- 複数 GPU 学習時に学習中のサンプル画像生成を複数 GPU で行うようになりました。 PR [#1061](https://github.com/kohya-ss/sd-scripts/pull/1061) DKnight54 氏に感謝します。
282+
- mps デバイスのサポートが改善されました。 PR [#1054](https://github.com/kohya-ss/sd-scripts/pull/1054) akx 氏に感謝します。CUDA ではなく mps が存在する場合には自動的に mps デバイスを使用します。
283+
- `networks/resize_lora.py` に Conv2d の新しいランクを指定するオプション `--new_conv_rank` が追加されました。 PR [#1102](https://github.com/kohya-ss/sd-scripts/pull/1102) mgz-dev 氏に感謝します。
284+
- 学習スクリプトに VRAMが少ない環境向け最適化を無効にするオプション `--highvram` を追加しました。VRAM に余裕がある場合に指定すると動作が高速化されます。
285+
- 現在は latents のキャッシュ部分のみ高速化されます。
286+
- IPEX サポートが改善されました。 PR [#1086](https://github.com/kohya-ss/sd-scripts/pull/1086) Disty0 氏に感謝します。
287+
- `svd_merge_lora.py` が場合によってエラーになる不具合が修正されました。 PR [#1087](https://github.com/kohya-ss/sd-scripts/pull/1087) mgz-dev 氏に感謝します。
288+
- DyLoRA が SDXL で動くよう修正されました。PR [#1126](https://github.com/kohya-ss/sd-scripts/pull/1126) tamlog06 氏に感謝します。
289+
- SD 1/2 および SDXL 共通の生成スクリプト `gen_img.py` を追加しました。基本的な機能は SD 1/2、SDXL 向けスクリプトと同じですが、いくつかの新機能が追加されています。
290+
- プロンプトを動的に生成する外部スクリプトをサポートしました。 `--from_module` で呼び出せます。(ドキュメントはのちほど追加します)
291+
- プロンプト重みづけ後の正規化方法を `--emb_normalize_mode` で指定できます。`original` は元の方法、`abs` は絶対値の平均値で正規化、`none` は正規化を行いません。
292+
- Gradual Latent Hires fix を各生成スクリプトに追加しました。詳細は [こちら](./docs/gen_img_README-ja.md#about-gradual-latent)
293+
294+
252295
### Jan 27, 2024 / 2024/1/27: v0.8.3
253296

254297
- Fixed a bug that the training crashes when `--fp8_base` is specified with `--save_state`. PR [#1079](https://github.com/kohya-ss/sd-scripts/pull/1079) Thanks to feffy380!
@@ -319,45 +362,6 @@ network_multiplier = -1.0
319362
```
320363

321364

322-
### Jan 17, 2024 / 2024/1/17: v0.8.1
323-
324-
- Fixed a bug that the VRAM usage without Text Encoder training is larger than before in training scripts for LoRA etc (`train_network.py`, `sdxl_train_network.py`).
325-
- Text Encoders were not moved to CPU.
326-
- Fixed typos. Thanks to akx! [PR #1053](https://github.com/kohya-ss/sd-scripts/pull/1053)
327-
328-
- LoRA 等の学習スクリプト(`train_network.py``sdxl_train_network.py`)で、Text Encoder を学習しない場合の VRAM 使用量が以前に比べて大きくなっていた不具合を修正しました。
329-
- Text Encoder が GPU に保持されたままになっていました。
330-
- 誤字が修正されました。 [PR #1053](https://github.com/kohya-ss/sd-scripts/pull/1053) akx 氏に感謝します。
331-
332-
### Jan 15, 2024 / 2024/1/15: v0.8.0
333-
334-
- Diffusers, Accelerate, Transformers and other related libraries have been updated. Please update the libraries with [Upgrade](#upgrade).
335-
- Some model files (Text Encoder without position_id) based on the latest Transformers can be loaded.
336-
- `torch.compile` is supported (experimental). PR [#1024](https://github.com/kohya-ss/sd-scripts/pull/1024) Thanks to p1atdev!
337-
- This feature works only on Linux or WSL.
338-
- Please specify `--torch_compile` option in each training script.
339-
- You can select the backend with `--dynamo_backend` option. The default is `"inductor"`. `inductor` or `eager` seems to work.
340-
- Please use `--sdpa` option instead of `--xformers` option.
341-
- PyTorch 2.1 or later is recommended.
342-
- Please see [PR](https://github.com/kohya-ss/sd-scripts/pull/1024) for details.
343-
- The session name for wandb can be specified with `--wandb_run_name` option. PR [#1032](https://github.com/kohya-ss/sd-scripts/pull/1032) Thanks to hopl1t!
344-
- IPEX library is updated. PR [#1030](https://github.com/kohya-ss/sd-scripts/pull/1030) Thanks to Disty0!
345-
- Fixed a bug that Diffusers format model cannot be saved.
346-
347-
- Diffusers、Accelerate、Transformers 等の関連ライブラリを更新しました。[Upgrade](#upgrade) を参照し更新をお願いします。
348-
- 最新の Transformers を前提とした一部のモデルファイル(Text Encoder が position_id を持たないもの)が読み込めるようになりました。
349-
- `torch.compile` がサポートされしました(実験的)。 PR [#1024](https://github.com/kohya-ss/sd-scripts/pull/1024) p1atdev 氏に感謝します。
350-
- Linux または WSL でのみ動作します。
351-
- 各学習スクリプトで `--torch_compile` オプションを指定してください。
352-
- `--dynamo_backend` オプションで使用される backend を選択できます。デフォルトは `"inductor"` です。 `inductor` または `eager` が動作するようです。
353-
- `--xformers` オプションとは互換性がありません。 代わりに `--sdpa` オプションを使用してください。
354-
- PyTorch 2.1以降を推奨します。
355-
- 詳細は [PR](https://github.com/kohya-ss/sd-scripts/pull/1024) をご覧ください。
356-
- wandb 保存時のセッション名が各学習スクリプトの `--wandb_run_name` オプションで指定できるようになりました。 PR [#1032](https://github.com/kohya-ss/sd-scripts/pull/1032) hopl1t 氏に感謝します。
357-
- IPEX ライブラリが更新されました。[PR #1030](https://github.com/kohya-ss/sd-scripts/pull/1030) Disty0 氏に感謝します。
358-
- Diffusers 形式でのモデル保存ができなくなっていた不具合を修正しました。
359-
360-
361365
Please read [Releases](https://github.com/kohya-ss/sd-scripts/releases) for recent updates.
362366
最近の更新情報は [Release](https://github.com/kohya-ss/sd-scripts/releases) をご覧ください。
363367

XTI_hijack.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import torch
2-
from library.ipex_interop import init_ipex
3-
2+
from library.device_utils import init_ipex
43
init_ipex()
4+
55
from typing import Union, List, Optional, Dict, Any, Tuple
66
from diffusers.models.unet_2d_condition import UNet2DConditionOutput
77

docs/gen_img_README-ja.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -452,3 +452,36 @@ python gen_img_diffusers.py --ckpt wd-v1-3-full-pruned-half.ckpt
452452

453453
- `--network_show_meta` : 追加ネットワークのメタデータを表示します。
454454

455+
456+
---
457+
458+
# About Gradual Latent
459+
460+
Gradual Latent is a Hires fix that gradually increases the size of the latent. `gen_img.py`, `sdxl_gen_img.py`, and `gen_img_diffusers.py` have the following options.
461+
462+
- `--gradual_latent_timesteps`: Specifies the timestep to start increasing the size of the latent. The default is None, which means Gradual Latent is not used. Please try around 750 at first.
463+
- `--gradual_latent_ratio`: Specifies the initial size of the latent. The default is 0.5, which means it starts with half the default latent size.
464+
- `--gradual_latent_ratio_step`: Specifies the ratio to increase the size of the latent. The default is 0.125, which means the latent size is gradually increased to 0.625, 0.75, 0.875, 1.0.
465+
- `--gradual_latent_ratio_every_n_steps`: Specifies the interval to increase the size of the latent. The default is 3, which means the latent size is increased every 3 steps.
466+
467+
Each option can also be specified with prompt options, `--glt`, `--glr`, `--gls`, `--gle`.
468+
469+
__Please specify `euler_a` for the sampler.__ Because the source code of the sampler is modified. It will not work with other samplers.
470+
471+
It is more effective with SD 1.5. It is quite subtle with SDXL.
472+
473+
# Gradual Latent について
474+
475+
latentのサイズを徐々に大きくしていくHires fixです。`gen_img.py` 、``sdxl_gen_img.py``gen_img_diffusers.py` に以下のオプションが追加されています。
476+
477+
- `--gradual_latent_timesteps` : latentのサイズを大きくし始めるタイムステップを指定します。デフォルトは None で、Gradual Latentを使用しません。750 くらいから始めてみてください。
478+
- `--gradual_latent_ratio` : latentの初期サイズを指定します。デフォルトは 0.5 で、デフォルトの latent サイズの半分のサイズから始めます。
479+
- `--gradual_latent_ratio_step`: latentのサイズを大きくする割合を指定します。デフォルトは 0.125 で、latentのサイズを 0.625, 0.75, 0.875, 1.0 と徐々に大きくします。
480+
- `--gradual_latent_ratio_every_n_steps`: latentのサイズを大きくする間隔を指定します。デフォルトは 3 で、3ステップごとに latent のサイズを大きくします。
481+
482+
それぞれのオプションは、プロンプトオプション、`--glt``--glr``--gls``--gle` でも指定できます。
483+
484+
サンプラーに手を加えているため、__サンプラーに `euler_a` を指定してください。__ 他のサンプラーでは動作しません。
485+
486+
SD 1.5 のほうが効果があります。SDXL ではかなり微妙です。
487+

fine_tune.py

Lines changed: 26 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,22 +2,27 @@
22
# XXX dropped option: hypernetwork training
33

44
import argparse
5-
import gc
65
import math
76
import os
87
from multiprocessing import Value
98
import toml
109

1110
from tqdm import tqdm
12-
import torch
13-
14-
from library.ipex_interop import init_ipex
1511

12+
import torch
13+
from library.device_utils import init_ipex, clean_memory_on_device
1614
init_ipex()
1715

1816
from accelerate.utils import set_seed
1917
from diffusers import DDPMScheduler
2018

19+
from library.utils import setup_logging, add_logging_arguments
20+
21+
setup_logging()
22+
import logging
23+
24+
logger = logging.getLogger(__name__)
25+
2126
import library.train_util as train_util
2227
import library.config_util as config_util
2328
from library.config_util import (
@@ -37,6 +42,7 @@
3742
def train(args):
3843
train_util.verify_training_args(args)
3944
train_util.prepare_dataset_args(args, True)
45+
setup_logging(args, reset=True)
4046

4147
cache_latents = args.cache_latents
4248

@@ -49,11 +55,11 @@ def train(args):
4955
if args.dataset_class is None:
5056
blueprint_generator = BlueprintGenerator(ConfigSanitizer(False, True, False, True))
5157
if args.dataset_config is not None:
52-
print(f"Load dataset config from {args.dataset_config}")
58+
logger.info(f"Load dataset config from {args.dataset_config}")
5359
user_config = config_util.load_user_config(args.dataset_config)
5460
ignored = ["train_data_dir", "in_json"]
5561
if any(getattr(args, attr) is not None for attr in ignored):
56-
print(
62+
logger.warning(
5763
"ignore following options because config file is found: {0} / 設定ファイルが利用されるため以下のオプションは無視されます: {0}".format(
5864
", ".join(ignored)
5965
)
@@ -86,7 +92,7 @@ def train(args):
8692
train_util.debug_dataset(train_dataset_group)
8793
return
8894
if len(train_dataset_group) == 0:
89-
print(
95+
logger.error(
9096
"No data found. Please verify the metadata file and train_data_dir option. / 画像がありません。メタデータおよびtrain_data_dirオプションを確認してください。"
9197
)
9298
return
@@ -97,7 +103,7 @@ def train(args):
97103
), "when caching latents, either color_aug or random_crop cannot be used / latentをキャッシュするときはcolor_augとrandom_cropは使えません"
98104

99105
# acceleratorを準備する
100-
print("prepare accelerator")
106+
logger.info("prepare accelerator")
101107
accelerator = train_util.prepare_accelerator(args)
102108

103109
# mixed precisionに対応した型を用意しておき適宜castする
@@ -158,9 +164,7 @@ def fn_recursive_set_mem_eff(module: torch.nn.Module):
158164
with torch.no_grad():
159165
train_dataset_group.cache_latents(vae, args.vae_batch_size, args.cache_latents_to_disk, accelerator.is_main_process)
160166
vae.to("cpu")
161-
if torch.cuda.is_available():
162-
torch.cuda.empty_cache()
163-
gc.collect()
167+
clean_memory_on_device(accelerator.device)
164168

165169
accelerator.wait_for_everyone()
166170

@@ -207,8 +211,8 @@ def fn_recursive_set_mem_eff(module: torch.nn.Module):
207211
_, _, optimizer = train_util.get_optimizer(args, trainable_params=trainable_params)
208212

209213
# dataloaderを準備する
210-
# DataLoaderのプロセス数:0はメインプロセスになる
211-
n_workers = min(args.max_data_loader_n_workers, os.cpu_count() - 1) # cpu_count-1 ただし最大で指定された数まで
214+
# DataLoaderのプロセス数:0 は persistent_workers が使えないので注意
215+
n_workers = min(args.max_data_loader_n_workers, os.cpu_count()) # cpu_count or max_data_loader_n_workers
212216
train_dataloader = torch.utils.data.DataLoader(
213217
train_dataset_group,
214218
batch_size=1,
@@ -223,7 +227,9 @@ def fn_recursive_set_mem_eff(module: torch.nn.Module):
223227
args.max_train_steps = args.max_train_epochs * math.ceil(
224228
len(train_dataloader) / accelerator.num_processes / args.gradient_accumulation_steps
225229
)
226-
accelerator.print(f"override steps. steps for {args.max_train_epochs} epochs is / 指定エポックまでのステップ数: {args.max_train_steps}")
230+
accelerator.print(
231+
f"override steps. steps for {args.max_train_epochs} epochs is / 指定エポックまでのステップ数: {args.max_train_steps}"
232+
)
227233

228234
# データセット側にも学習ステップを送信
229235
train_dataset_group.set_max_train_steps(args.max_train_steps)
@@ -287,7 +293,7 @@ def fn_recursive_set_mem_eff(module: torch.nn.Module):
287293
if accelerator.is_main_process:
288294
init_kwargs = {}
289295
if args.wandb_run_name:
290-
init_kwargs['wandb'] = {'name': args.wandb_run_name}
296+
init_kwargs["wandb"] = {"name": args.wandb_run_name}
291297
if args.log_tracker_config is not None:
292298
init_kwargs = toml.load(args.log_tracker_config)
293299
accelerator.init_trackers("finetuning" if args.log_tracker_name is None else args.log_tracker_name, init_kwargs=init_kwargs)
@@ -461,12 +467,13 @@ def fn_recursive_set_mem_eff(module: torch.nn.Module):
461467
train_util.save_sd_model_on_train_end(
462468
args, src_path, save_stable_diffusion_format, use_safetensors, save_dtype, epoch, global_step, text_encoder, unet, vae
463469
)
464-
print("model saved.")
470+
logger.info("model saved.")
465471

466472

467473
def setup_parser() -> argparse.ArgumentParser:
468474
parser = argparse.ArgumentParser()
469475

476+
add_logging_arguments(parser)
470477
train_util.add_sd_models_arguments(parser)
471478
train_util.add_dataset_arguments(parser, False, True, True)
472479
train_util.add_training_arguments(parser, False)
@@ -475,7 +482,9 @@ def setup_parser() -> argparse.ArgumentParser:
475482
config_util.add_config_arguments(parser)
476483
custom_train_functions.add_custom_train_arguments(parser)
477484

478-
parser.add_argument("--diffusers_xformers", action="store_true", help="use xformers by diffusers / Diffusersでxformersを使用する")
485+
parser.add_argument(
486+
"--diffusers_xformers", action="store_true", help="use xformers by diffusers / Diffusersでxformersを使用する"
487+
)
479488
parser.add_argument("--train_text_encoder", action="store_true", help="train text encoder / text encoderも学習する")
480489
parser.add_argument(
481490
"--learning_rate_te",

finetune/blip/blip.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,10 @@
2121
import os
2222
from urllib.parse import urlparse
2323
from timm.models.hub import download_cached_file
24+
from library.utils import setup_logging
25+
setup_logging()
26+
import logging
27+
logger = logging.getLogger(__name__)
2428

2529
class BLIP_Base(nn.Module):
2630
def __init__(self,
@@ -235,6 +239,6 @@ def load_checkpoint(model,url_or_filename):
235239
del state_dict[key]
236240

237241
msg = model.load_state_dict(state_dict,strict=False)
238-
print('load checkpoint from %s'%url_or_filename)
242+
logger.info('load checkpoint from %s'%url_or_filename)
239243
return model,msg
240244

0 commit comments

Comments
 (0)