From 8f5a2eba3db83b6651fb99745368551132782816 Mon Sep 17 00:00:00 2001 From: Kohya S Date: Fri, 11 Apr 2025 08:07:24 +0900 Subject: [PATCH 1/9] Add documentation for LoRA training scripts for SD1/2, SDXL, FLUX.1 and SD3/3.5 models --- docs/flux_train_network.md | 127 +++++++++++++++ docs/sd3_train_network.md | 122 ++++++++++++++ docs/sdxl_train_network.md | 160 +++++++++++++++++++ docs/train_network.md | 314 +++++++++++++++++++++++++++++++++++++ 4 files changed, 723 insertions(+) create mode 100644 docs/flux_train_network.md create mode 100644 docs/sd3_train_network.md create mode 100644 docs/sdxl_train_network.md create mode 100644 docs/train_network.md diff --git a/docs/flux_train_network.md b/docs/flux_train_network.md new file mode 100644 index 00000000..d28d5877 --- /dev/null +++ b/docs/flux_train_network.md @@ -0,0 +1,127 @@ +# `flux_train_network.py` を用いたFLUX.1モデルのLoRA学習ガイド + +このドキュメントでは、`sd-scripts`リポジトリに含まれる`flux_train_network.py`を使用して、FLUX.1モデルに対するLoRA (Low-Rank Adaptation) モデルを学習する基本的な手順について解説します。 + +## 1. はじめに + +`flux_train_network.py`は、FLUX.1モデルに対してLoRAなどの追加ネットワークを学習させるためのスクリプトです。FLUX.1はStable Diffusionとは異なるアーキテクチャを持つ画像生成モデルであり、このスクリプトを使用することで、特定のキャラクターや画風を再現するLoRAモデルを作成できます。 + +このガイドは、基本的なLoRA学習の手順を理解しているユーザーを対象とし、`train_network.py`での学習経験があることを前提としています。基本的な使い方や共通のオプションについては、[`train_network.py`のガイド](how_to_use_train_network.md)を参照してください。 + +**前提条件:** + +* `sd-scripts`リポジトリのクローンとPython環境のセットアップが完了していること。 +* 学習用データセットの準備が完了していること。(データセットの準備については[データセット設定ガイド](link/to/dataset/config/doc)を参照してください) + +## 2. `train_network.py` との違い + +`flux_train_network.py`は`train_network.py`をベースに、FLUX.1モデルに対応するための変更が加えられています。主な違いは以下の通りです。 + +* **対象モデル:** FLUX.1モデル(dev版またはschnell版)を対象とします。 +* **モデル構造:** Stable Diffusionとは異なり、FLUX.1はTransformerベースのアーキテクチャを持ちます。Text EncoderとしてCLIP-LとT5-XXLの二つを使用し、VAEの代わりに専用のAutoEncoder (AE) を使用します。 +* **必須の引数:** FLUX.1モデル、CLIP-L、T5-XXL、AEの各モデルファイルを指定する引数が追加されています。 +* **一部引数の非互換性:** Stable Diffusion向けの引数の一部(例: `--v2`, `--clip_skip`, `--max_token_length`)はFLUX.1の学習では使用されません。 +* **FLUX.1特有の引数:** タイムステップのサンプリング方法やガイダンススケールなど、FLUX.1特有の学習パラメータを指定する引数が追加されています。 + +## 3. 準備 + +学習を開始する前に、以下のファイルが必要です。 + +1. **学習スクリプト:** `flux_train_network.py` +2. **FLUX.1モデルファイル:** 学習のベースとなるFLUX.1モデルの`.safetensors`ファイル(例: `flux1-dev.safetensors`)。 +3. **Text Encoderモデルファイル:** + * CLIP-Lモデルの`.safetensors`ファイル。 + * T5-XXLモデルの`.safetensors`ファイル。 +4. **AutoEncoderモデルファイル:** FLUX.1に対応するAEモデルの`.safetensors`ファイル。 +5. **データセット定義ファイル (.toml):** 学習データセットの設定を記述したTOML形式のファイル。(詳細は[データセット設定ガイド](link/to/dataset/config/doc)を参照してください)。 + + * 例として`my_flux_dataset_config.toml`を使用します。 + +## 4. 学習の実行 + +学習は、ターミナルから`flux_train_network.py`を実行することで開始します。基本的なコマンドラインの構造は`train_network.py`と同様ですが、FLUX.1特有の引数を指定する必要があります。 + +以下に、基本的なコマンドライン実行例を示します。 + +```bash +accelerate launch --num_cpu_threads_per_process 1 flux_train_network.py + --pretrained_model_name_or_path="" + --clip_l="" + --t5xxl="" + --ae="" + --dataset_config="my_flux_dataset_config.toml" + --output_dir="" + --output_name="my_flux_lora" + --save_model_as=safetensors + --network_module=networks.lora + --network_dim=16 + --network_alpha=1 + --learning_rate=1e-4 + --optimizer_type="AdamW8bit" + --lr_scheduler="constant" + --sdpa + --max_train_epochs=10 + --save_every_n_epochs=1 + --mixed_precision="fp16" + --gradient_checkpointing + --apply_t5_attn_mask + --blocks_to_swap=18 +``` + +※実際には1行で書くか、適切な改行文字(`\` または `^`)を使用してください。 + +### 4.1. 主要なコマンドライン引数の解説(`train_network.py`からの追加・変更点) + +[`train_network.py`のガイド](how_to_use_train_network.md)で説明されている引数に加え、以下のFLUX.1特有の引数を指定します。共通の引数(`--output_dir`, `--output_name`, `--network_module`, `--network_dim`, `--network_alpha`, `--learning_rate`など)については、上記ガイドを参照してください。 + +#### モデル関連 [必須] + +* `--pretrained_model_name_or_path=""` **[必須]** + * 学習のベースとなるFLUX.1モデル(dev版またはschnell版)の`.safetensors`ファイルのパスを指定します。Diffusers形式のディレクトリは現在サポートされていません。 +* `--clip_l=""` **[必須]** + * CLIP-L Text Encoderモデルの`.safetensors`ファイルのパスを指定します。 +* `--t5xxl=""` **[必須]** + * T5-XXL Text Encoderモデルの`.safetensors`ファイルのパスを指定します。 +* `--ae=""` **[必須]** + * FLUX.1に対応するAutoEncoderモデルの`.safetensors`ファイルのパスを指定します。 + +#### FLUX.1 学習パラメータ + +* `--t5xxl_max_token_length=` + * T5-XXL Text Encoderで使用するトークンの最大長を指定します。省略した場合、モデルがschnell版なら256、dev版なら512が自動的に設定されます。データセットのキャプション長に合わせて調整が必要な場合があります。 +* `--apply_t5_attn_mask` + * T5-XXLの出力とFLUXモデル内部(Double Block)のアテンション計算時に、パディングトークンに対応するアテンションマスクを適用します。精度向上が期待できる場合がありますが、わずかに計算コストが増加します。 +* `--guidance_scale=` + * FLUX.1 dev版は特定のガイダンススケール値で蒸留されているため、学習時にもその値を指定します。デフォルトは`3.5`です。schnell版では通常無視されます。 +* `--timestep_sampling=` + * 学習時に使用するタイムステップ(ノイズレベル)のサンプリング方法を指定します。`sigma`, `uniform`, `sigmoid`, `shift`, `flux_shift` から選択します。デフォルトは `sigma` です。 +* `--sigmoid_scale=` + * `timestep_sampling` に `sigmoid` または `shift`, `flux_shift` を指定した場合のスケール係数です。デフォルトは`1.0`です。 +* `--model_prediction_type=` + * モデルが何を予測するかを指定します。`raw` (予測値をそのまま使用), `additive` (ノイズ入力に加算), `sigma_scaled` (シグマスケーリングを適用) から選択します。デフォルトは `sigma_scaled` です。 +* `--discrete_flow_shift=` + * Flow Matchingで使用されるスケジューラのシフト値を指定します。デフォルトは`3.0`です。 + +#### メモリ・速度関連 + +* `--blocks_to_swap=` **[実験的機能]** + * VRAM使用量を削減するために、モデルの一部(Transformerブロック)をCPUとGPU間でスワップする設定です。スワップするブロック数を整数で指定します(例: `18`)。値を大きくするとVRAM使用量は減りますが、学習速度は低下します。GPUのVRAM容量に応じて調整してください。`gradient_checkpointing`と併用可能です。 + * `--cpu_offload_checkpointing`とは併用できません。 + +#### 非互換・非推奨の引数 + +* `--v2`, `--v_parameterization`, `--clip_skip`: Stable Diffusion特有の引数のため、FLUX.1学習では使用されません。 +* `--max_token_length`: Stable Diffusion v1/v2向けの引数です。FLUX.1では`--t5xxl_max_token_length`を使用してください。 +* `--split_mode`: 非推奨の引数です。代わりに`--blocks_to_swap`を使用してください。 + +### 4.2. 学習の開始 + +必要な引数を設定し、コマンドを実行すると学習が開始されます。基本的な流れやログの確認方法は[`train_network.py`のガイド](how_to_use_train_network.md#32-starting-the-training--学習の開始)と同様です。 + +## 5. 学習済みモデルの利用 + +学習が完了すると、指定した`output_dir`にLoRAモデルファイル(例: `my_flux_lora.safetensors`)が保存されます。このファイルは、FLUX.1モデルに対応した推論環境(例: ComfyUI + ComfyUI-FluxNodes)で使用できます。 + +## 6. その他 + +`flux_train_network.py`には、サンプル画像の生成 (`--sample_prompts`など) や詳細なオプティマイザ設定など、`train_network.py`と共通の機能も多く存在します。これらについては、[`train_network.py`のガイド](how_to_use_train_network.md#5-other-features--その他の機能)やスクリプトのヘルプ (`python flux_train_network.py --help`) を参照してください。 diff --git a/docs/sd3_train_network.md b/docs/sd3_train_network.md new file mode 100644 index 00000000..d5cc5a75 --- /dev/null +++ b/docs/sd3_train_network.md @@ -0,0 +1,122 @@ +# `sd3_train_network.py` を用いたStable Diffusion 3/3.5モデルのLoRA学習ガイド + +このドキュメントでは、`sd-scripts`リポジトリに含まれる`sd3_train_network.py`を使用して、Stable Diffusion 3 (SD3) および Stable Diffusion 3.5 (SD3.5) モデルに対するLoRA (Low-Rank Adaptation) モデルを学習する基本的な手順について解説します。 + +## 1. はじめに + +`sd3_train_network.py`は、Stable Diffusion 3/3.5モデルに対してLoRAなどの追加ネットワークを学習させるためのスクリプトです。SD3は、MMDiT (Multi-Modal Diffusion Transformer) と呼ばれる新しいアーキテクチャを採用しており、従来のStable Diffusionモデルとは構造が異なります。このスクリプトを使用することで、SD3/3.5モデルに特化したLoRAモデルを作成できます。 + +このガイドは、基本的なLoRA学習の手順を理解しているユーザーを対象とし、`train_network.py`での学習経験があることを前提としています。基本的な使い方や共通のオプションについては、[`train_network.py`のガイド](how_to_use_train_network.md)を参照してください。 + +**前提条件:** + +* `sd-scripts`リポジトリのクローンとPython環境のセットアップが完了していること。 +* 学習用データセットの準備が完了していること。(データセットの準備については[データセット設定ガイド](link/to/dataset/config/doc)を参照してください) +* 学習対象のSD3/3.5モデルファイルが準備できていること。 + +## 2. `train_network.py` との違い + +`sd3_train_network.py`は`train_network.py`をベースに、SD3/3.5モデルに対応するための変更が加えられています。主な違いは以下の通りです。 + +* **対象モデル:** Stable Diffusion 3 Medium / Large (3.0 / 3.5) モデルを対象とします。 +* **モデル構造:** U-Netの代わりにMMDiT (Transformerベース) を使用します。Text EncoderとしてCLIP-L, CLIP-G, T5-XXLの三つを使用します。VAEはSDXLと互換性がありますが、入力のスケール処理が異なります。 +* **引数:** SD3/3.5モデル、Text Encoder群、VAEを指定する引数があります。ただし、単一ファイルの`.safetensors`形式であれば、内部で自動的に分離されるため、個別のパス指定は必須ではありません。 +* **一部引数の非互換性:** Stable Diffusion v1/v2向けの引数(例: `--v2`, `--v_parameterization`, `--clip_skip`)はSD3/3.5の学習では使用されません。 +* **SD3特有の引数:** Text Encoderのアテンションマスクやドロップアウト率、Positional Embeddingの調整(SD3.5向け)、タイムステップのサンプリングや損失の重み付けに関する引数が追加されています。 + +## 3. 準備 + +学習を開始する前に、以下のファイルが必要です。 + +1. **学習スクリプト:** `sd3_train_network.py` +2. **SD3/3.5モデルファイル:** 学習のベースとなるSD3/3.5モデルの`.safetensors`ファイル。単一ファイル形式(Diffusers/ComfyUI/AUTOMATIC1111形式)を推奨します。 + * Text EncoderやVAEが別ファイルになっている場合は、対応する引数でパスを指定します。 +3. **データセット定義ファイル (.toml):** 学習データセットの設定を記述したTOML形式のファイル。(詳細は[データセット設定ガイド](link/to/dataset/config/doc)を参照してください)。 + * 例として`my_sd3_dataset_config.toml`を使用します。 + +## 4. 学習の実行 + +学習は、ターミナルから`sd3_train_network.py`を実行することで開始します。基本的なコマンドラインの構造は`train_network.py`と同様ですが、SD3/3.5特有の引数を指定する必要があります。 + +以下に、基本的なコマンドライン実行例を示します。 + +```bash +accelerate launch --num_cpu_threads_per_process 1 sd3_train_network.py + --pretrained_model_name_or_path="" + --dataset_config="my_sd3_dataset_config.toml" + --output_dir="" + --output_name="my_sd3_lora" + --save_model_as=safetensors + --network_module=networks.lora + --network_dim=16 + --network_alpha=1 + --learning_rate=1e-4 + --optimizer_type="AdamW8bit" + --lr_scheduler="constant" + --sdpa + --max_train_epochs=10 + --save_every_n_epochs=1 + --mixed_precision="fp16" + --gradient_checkpointing + --apply_lg_attn_mask + --apply_t5_attn_mask + --weighting_scheme="sigma_sqrt" + --blocks_to_swap=32 +``` + +※実際には1行で書くか、適切な改行文字(`\` または `^`)を使用してください。 + +### 4.1. 主要なコマンドライン引数の解説(`train_network.py`からの追加・変更点) + +[`train_network.py`のガイド](how_to_use_train_network.md)で説明されている引数に加え、以下のSD3/3.5特有の引数を指定します。共通の引数(`--output_dir`, `--output_name`, `--network_module`, `--network_dim`, `--network_alpha`, `--learning_rate`など)については、上記ガイドを参照してください。 + +#### モデル関連 + +* `--pretrained_model_name_or_path=""` **[必須]** + * 学習のベースとなるSD3/3.5モデルの`.safetensors`ファイルのパスを指定します。単一ファイル形式(Diffusers/ComfyUI/AUTOMATIC1111形式)を想定しています。 +* `--clip_l`, `--clip_g`, `--t5xxl`, `--vae`: + * ベースモデルが単一ファイル形式の場合、通常これらの指定は不要です(自動的にモデル内部から読み込まれます)。 + * もしText EncoderやVAEが別ファイルとして提供されている場合は、それぞれの`.safetensors`ファイルのパスを指定します。 + +#### SD3/3.5 学習パラメータ + +* `--t5xxl_max_token_length=` + * T5-XXL Text Encoderで使用するトークンの最大長を指定します。SD3のデフォルトは`256`です。データセットのキャプション長に合わせて調整が必要な場合があります。 +* `--apply_lg_attn_mask` + * CLIP-LおよびCLIP-Gの出力に対して、パディングトークンに対応するアテンションマスク(ゼロ埋め)を適用します。 +* `--apply_t5_attn_mask` + * T5-XXLの出力に対して、パディングトークンに対応するアテンションマスク(ゼロ埋め)を適用します。 +* `--clip_l_dropout_rate`, `--clip_g_dropout_rate`, `--t5_dropout_rate`: + * 各Text Encoderの出力に対して、指定した確率でドロップアウト(出力をゼロにする)を適用します。過学習の抑制に役立つ場合があります。デフォルトは`0.0`(ドロップアウトなし)です。 +* `--pos_emb_random_crop_rate=` **[SD3.5向け]** + * MMDiTのPositional Embeddingに対してランダムクロップを適用する確率を指定します。SD3 5M (3.5) モデルで学習された機能であり、他のモデルでの効果は限定的です。デフォルトは`0.0`です。 +* `--enable_scaled_pos_embed` **[SD3.5向け]** + * マルチ解像度学習時に、解像度に応じてPositional Embeddingをスケーリングします。SD3 5M (3.5) モデルで学習された機能であり、他のモデルでの効果は限定的です。 +* `--training_shift=` + * 学習時のタイムステップ(ノイズレベル)の分布を調整するためのシフト値です。`weighting_scheme`に加えて適用されます。`1.0`より大きい値はノイズの大きい(構造寄り)領域を、小さい値はノイズの小さい(詳細寄り)領域を重視する傾向になります。デフォルトは`1.0`です。 +* `--weighting_scheme=` + * 損失計算時のタイムステップ(ノイズレベル)に応じた重み付け方法を指定します。`sigma_sqrt`, `logit_normal`, `mode`, `cosmap`, `uniform` (または`none`) から選択します。SD3の論文では`sigma_sqrt`が使用されています。デフォルトは`uniform`です。 +* `--logit_mean`, `--logit_std`, `--mode_scale`: + * `weighting_scheme`で`logit_normal`または`mode`を選択した場合に、その分布を制御するためのパラメータです。通常はデフォルト値で問題ありません。 + +#### メモリ・速度関連 + +* `--blocks_to_swap=` **[実験的機能]** + * VRAM使用量を削減するために、モデルの一部(MMDiTのTransformerブロック)をCPUとGPU間でスワップする設定です。スワップするブロック数を整数で指定します(例: `32`)。値を大きくするとVRAM使用量は減りますが、学習速度は低下します。GPUのVRAM容量に応じて調整してください。`gradient_checkpointing`と併用可能です。 + * `--cpu_offload_checkpointing`とは併用できません。 + +#### 非互換・非推奨の引数 + +* `--v2`, `--v_parameterization`, `--clip_skip`: Stable Diffusion v1/v2特有の引数のため、SD3/3.5学習では使用されません。 + +### 4.2. 学習の開始 + +必要な引数を設定し、コマンドを実行すると学習が開始されます。基本的な流れやログの確認方法は[`train_network.py`のガイド](how_to_use_train_network.md#32-starting-the-training--学習の開始)と同様です。 + +## 5. 学習済みモデルの利用 + +学習が完了すると、指定した`output_dir`にLoRAモデルファイル(例: `my_sd3_lora.safetensors`)が保存されます。このファイルは、SD3/3.5モデルに対応した推論環境(例: ComfyUIなど)で使用できます。 + +## 6. その他 + +`sd3_train_network.py`には、サンプル画像の生成 (`--sample_prompts`など) や詳細なオプティマイザ設定など、`train_network.py`と共通の機能も多く存在します。これらについては、[`train_network.py`のガイド](how_to_use_train_network.md#5-other-features--その他の機能)やスクリプトのヘルプ (`python sd3_train_network.py --help`) を参照してください。 diff --git a/docs/sdxl_train_network.md b/docs/sdxl_train_network.md new file mode 100644 index 00000000..8a19f7ae --- /dev/null +++ b/docs/sdxl_train_network.md @@ -0,0 +1,160 @@ +はい、承知いたしました。`sd-scripts` リポジトリに含まれる `sdxl_train_network.py` を使用した SDXL LoRA 学習に関するドキュメントを作成します。`how_to_use_train_network.md` との差分を中心に、初心者ユーザー向けに解説します。 + +--- + +# SDXL LoRA学習スクリプト `sdxl_train_network.py` の使い方 + +このドキュメントでは、`sd-scripts` リポジトリに含まれる `sdxl_train_network.py` を使用して、SDXL (Stable Diffusion XL) モデルに対する LoRA (Low-Rank Adaptation) モデルを学習する基本的な手順について解説します。 + +## 1. はじめに + +`sdxl_train_network.py` は、SDXL モデルに対して LoRA などの追加ネットワークを学習させるためのスクリプトです。基本的な使い方は `train_network.py` ([LoRA学習スクリプト `train_network.py` の使い方](how_to_use_train_network.md) 参照) と共通ですが、SDXL モデル特有の設定が必要となります。 + +このガイドでは、SDXL LoRA 学習に焦点を当て、`train_network.py` との主な違いや SDXL 特有の設定項目を中心に説明します。 + +**前提条件:** + +* `sd-scripts` リポジトリのクローンと Python 環境のセットアップが完了していること。 +* 学習用データセットの準備が完了していること。(データセットの準備については[データセット準備ガイド](link/to/dataset/doc)を参照してください) +* [LoRA学習スクリプト `train_network.py` の使い方](how_to_use_train_network.md) を一読していること。 + +## 2. 準備 + +学習を開始する前に、以下のファイルが必要です。 + +1. **学習スクリプト:** `sdxl_train_network.py` +2. **データセット定義ファイル (.toml):** 学習データセットの設定を記述した TOML 形式のファイル。 + +### データセット定義ファイルについて + +データセット定義ファイル (`.toml`) の基本的な書き方は `train_network.py` と共通です。[データセット設定ガイド](link/to/dataset/config/doc) および [LoRA学習スクリプト `train_network.py` の使い方](how_to_use_train_network.md#データセット定義ファイルについて) を参照してください。 + +SDXL では、高解像度のデータセットや、アスペクト比バケツ機能 (`enable_bucket = true`) の利用が一般的です。 + +ここでは、例として `my_sdxl_dataset_config.toml` という名前のファイルを使用することにします。 + +## 3. 学習の実行 + +学習は、ターミナルから `sdxl_train_network.py` を実行することで開始します。 + +以下に、SDXL LoRA 学習における基本的なコマンドライン実行例を示します。 + +```bash +accelerate launch --num_cpu_threads_per_process 1 sdxl_train_network.py + --pretrained_model_name_or_path="" + --dataset_config="my_sdxl_dataset_config.toml" + --output_dir="<学習結果の出力先ディレクトリ>" + --output_name="my_sdxl_lora" + --save_model_as=safetensors + --network_module=networks.lora + --network_dim=32 + --network_alpha=16 + --learning_rate=1e-4 + --unet_lr=1e-4 + --text_encoder_lr1=1e-5 + --text_encoder_lr2=1e-5 + --optimizer_type="AdamW8bit" + --lr_scheduler="constant" + --max_train_epochs=10 + --save_every_n_epochs=1 + --mixed_precision="bf16" + --gradient_checkpointing + --cache_text_encoder_outputs + --cache_latents +``` + +`train_network.py` の実行例と比較すると、以下の点が異なります。 + +* 実行するスクリプトが `sdxl_train_network.py` になります。 +* `--pretrained_model_name_or_path` には SDXL のベースモデルを指定します。 +* `--text_encoder_lr` が `--text_encoder_lr1` と `--text_encoder_lr2` に分かれています(SDXL は2つの Text Encoder を持つため)。 +* `--mixed_precision` は `bf16` または `fp16` が推奨されます。 +* `--cache_text_encoder_outputs` や `--cache_latents` は VRAM 使用量を削減するために推奨されます。 + +次に、`train_network.py` との差分となる主要なコマンドライン引数について解説します。共通の引数については、[LoRA学習スクリプト `train_network.py` の使い方](how_to_use_train_network.md#31-主要なコマンドライン引数) を参照してください。 + +### 3.1. 主要なコマンドライン引数(差分) + +#### モデル関連 + +* `--pretrained_model_name_or_path="<モデルのパス>"` **[必須]** + * 学習のベースとなる **SDXL モデル**を指定します。Hugging Face Hub のモデル ID (例: `"stabilityai/stable-diffusion-xl-base-1.0"`) や、ローカルの Diffusers 形式モデルのディレクトリ、`.safetensors` ファイルのパスを指定できます。 +* `--v2`, `--v_parameterization` + * これらの引数は SD1.x/2.x 用です。`sdxl_train_network.py` を使用する場合、SDXL モデルであることが前提となるため、通常は**指定する必要はありません**。 + +#### データセット関連 + +* `--dataset_config="<設定ファイルのパス>"` + * `train_network.py` と共通です。 + * SDXL では高解像度データやバケツ機能 (`.toml` で `enable_bucket = true` を指定) の利用が一般的です。 + +#### 出力・保存関連 + +* `train_network.py` と共通です。 + +#### LoRA パラメータ + +* `train_network.py` と共通です。 + +#### 学習パラメータ + +* `--learning_rate=1e-4` + * 全体の学習率。`unet_lr`, `text_encoder_lr1`, `text_encoder_lr2` が指定されない場合のデフォルト値となります。 +* `--unet_lr=1e-4` + * U-Net 部分の LoRA モジュールに対する学習率。指定しない場合は `--learning_rate` の値が使用されます。 +* `--text_encoder_lr1=1e-5` + * **Text Encoder 1 (OpenCLIP ViT-G/14) の LoRA モジュール**に対する学習率。指定しない場合は `--learning_rate` の値が使用されます。U-Net より小さめの値が推奨されます。 +* `--text_encoder_lr2=1e-5` + * **Text Encoder 2 (CLIP ViT-L/14) の LoRA モジュール**に対する学習率。指定しない場合は `--learning_rate` の値が使用されます。U-Net より小さめの値が推奨されます。 +* `--optimizer_type="AdamW8bit"` + * `train_network.py` と共通です。 +* `--lr_scheduler="constant"` + * `train_network.py` と共通です。 +* `--lr_warmup_steps` + * `train_network.py` と共通です。 +* `--max_train_steps`, `--max_train_epochs` + * `train_network.py` と共通です。 +* `--mixed_precision="bf16"` + * 混合精度学習の設定。SDXL では `bf16` または `fp16` の使用が推奨されます。GPU が対応している方を選択してください。VRAM 使用量を削減し、学習速度を向上させます。 +* `--gradient_accumulation_steps=1` + * `train_network.py` と共通です。 +* `--gradient_checkpointing` + * `train_network.py` と共通です。SDXL はメモリ消費が大きいため、有効にすることが推奨されます。 +* `--cache_latents` + * VAE の出力をメモリ(または `--cache_latents_to_disk` 指定時はディスク)にキャッシュします。VAE の計算を省略できるため、VRAM 使用量を削減し、学習を高速化できます。画像に対する Augmentation (`--color_aug`, `--flip_aug`, `--random_crop` 等) が無効になります。SDXL 学習では推奨されるオプションです。 +* `--cache_latents_to_disk` + * `--cache_latents` と併用し、キャッシュ先をディスクにします。データセットを最初に読み込む際に、VAE の出力をディスクにキャッシュします。二回目以降の学習で VAE の計算を省略できるため、学習データの枚数が多い場合に推奨されます。 +* `--cache_text_encoder_outputs` + * Text Encoder の出力をメモリ(または `--cache_text_encoder_outputs_to_disk` 指定時はディスク)にキャッシュします。Text Encoder の計算を省略できるため、VRAM 使用量を削減し、学習を高速化できます。キャプションに対する Augmentation (`--shuffle_caption`, `--caption_dropout_rate` 等) が無効になります。 + * **注意:** このオプションを使用する場合、Text Encoder の LoRA モジュールは学習できません (`--network_train_unet_only` の指定が必須です)。 +* `--cache_text_encoder_outputs_to_disk` + * `--cache_text_encoder_outputs` と併用し、キャッシュ先をディスクにします。 +* `--no_half_vae` + * 混合精度 (`fp16`/`bf16`) 使用時でも VAE を `float32` で動作させます。SDXL の VAE は `float16` で不安定になることがあるため、`fp16` 指定時には有効にしてくだ +* `--clip_skip` + * SDXL では通常使用しません。指定は不要です。 +* `--fused_backward_pass` + * 勾配計算とオプティマイザのステップを融合し、VRAM使用量を削減します。SDXLで利用可能です。(現在 `Adafactor` オプティマイザのみ対応) + +#### その他 + +* `--seed`, `--logging_dir`, `--log_prefix` などは `train_network.py` と共通です。 + +### 3.2. 学習の開始 + +必要な引数を設定し、コマンドを実行すると学習が開始されます。学習の進行状況はコンソールに出力されます。基本的な流れは `train_network.py` と同じです。 + +## 4. 学習済みモデルの利用 + +学習が完了すると、`output_dir` で指定したディレクトリに、`output_name` で指定した名前の LoRA モデルファイル (`.safetensors` など) が保存されます。 + +このファイルは、AUTOMATIC1111/stable-diffusion-webui 、ComfyUI などの SDXL に対応した GUI ツールで利用できます。 + +## 5. 補足: `train_network.py` との主な違い + +* **対象モデル:** `sdxl_train_network.py` は SDXL モデル専用です。 +* **Text Encoder:** SDXL は 2 つの Text Encoder を持つため、学習率の指定 (`--text_encoder_lr1`, `--text_encoder_lr2`) などが異なります。 +* **キャッシュ機能:** `--cache_text_encoder_outputs` は SDXL で特に効果が高く、推奨されます。 +* **推奨設定:** VRAM 使用量が大きいため、`bf16` または `fp16` の混合精度、`gradient_checkpointing`、キャッシュ機能 (`--cache_latents`, `--cache_text_encoder_outputs`) の利用が推奨されます。`fp16` 指定時は、VAE は `--no_half_vae` で `float32` 動作を推奨します。 + +その他の詳細なオプションについては、スクリプトのヘルプ (`python sdxl_train_network.py --help`) やリポジトリ内の他のドキュメントを参照してください。 \ No newline at end of file diff --git a/docs/train_network.md b/docs/train_network.md new file mode 100644 index 00000000..06c08a42 --- /dev/null +++ b/docs/train_network.md @@ -0,0 +1,314 @@ +# How to use the LoRA training script `train_network.py` / LoRA学習スクリプト `train_network.py` の使い方 + +This document explains the basic procedures for training LoRA (Low-Rank Adaptation) models using `train_network.py` included in the `sd-scripts` repository. + +
+日本語 +このドキュメントでは、`sd-scripts` リポジトリに含まれる `train_network.py` を使用して LoRA (Low-Rank Adaptation) モデルを学習する基本的な手順について解説します。 +
+ +## 1. Introduction / はじめに + +`train_network.py` is a script for training additional networks such as LoRA on Stable Diffusion models (v1.x, v2.x). It allows for additional training on the original model with a low computational cost, enabling the creation of models that reproduce specific characters or art styles. + +This guide focuses on LoRA training and explains the basic configuration items. + +**Prerequisites:** + +* The `sd-scripts` repository has been cloned and the Python environment has been set up. +* The training dataset has been prepared. (For dataset preparation, please refer to [this guide](link/to/dataset/doc)) + +
+日本語 + +`train_network.py` は、Stable Diffusion モデル(v1.x, v2.x)に対して、LoRA などの追加ネットワークを学習させるためのスクリプトです。少ない計算コストで元のモデルに追加学習を行い、特定のキャラクターや画風を再現するモデルを作成できます。 + +このガイドでは、LoRA 学習に焦点を当て、基本的な設定項目を中心に説明します。 + +**前提条件:** + +* `sd-scripts` リポジトリのクローンと Python 環境のセットアップが完了していること。 +* 学習用データセットの準備が完了していること。(データセットの準備については[こちら](link/to/dataset/doc)を参照してください) +
+ +## 2. Preparation / 準備 + +Before starting training, you will need the following files: + +1. **Training script:** `train_network.py` +2. **Dataset definition file (.toml):** A file in TOML format that describes the configuration of the training dataset. + +### About the Dataset Definition File / データセット定義ファイルについて + +The dataset definition file (`.toml`) contains detailed settings such as the directory of images to use, repetition count, caption settings, resolution buckets (optional), etc. + +For more details on how to write the dataset definition file, please refer to the [Dataset Configuration Guide](link/to/dataset/config/doc). + +In this guide, we will use a file named `my_dataset_config.toml` as an example. + +
+日本語 + +学習を開始する前に、以下のファイルが必要です。 + +1. **学習スクリプト:** `train_network.py` +2. **データセット定義ファイル (.toml):** 学習データセットの設定を記述した TOML 形式のファイル。 + +**データセット定義ファイルについて** + +データセット定義ファイル (`.toml`) には、使用する画像のディレクトリ、繰り返し回数、キャプションの設定、解像度バケツ(任意)などの詳細な設定を記述します。 + +データセット定義ファイルの詳しい書き方については、[データセット設定ガイド](link/to/dataset/config/doc)を参照してください。 + +ここでは、例として `my_dataset_config.toml` という名前のファイルを使用することにします。 +
+ +## 3. Running the Training / 学習の実行 + +Training is started by executing `train_network.py` from the terminal. When executing, various training settings are specified as command-line arguments. + +Below is a basic command-line execution example: + +```bash +accelerate launch --num_cpu_threads_per_process 1 train_network.py + --pretrained_model_name_or_path="" + --dataset_config="my_dataset_config.toml" + --output_dir="" + --output_name="my_lora" + --save_model_as=safetensors + --network_module=networks.lora + --network_dim=16 + --network_alpha=1 + --learning_rate=1e-4 + --optimizer_type="AdamW8bit" + --lr_scheduler="constant" + --sdpa + --max_train_epochs=10 + --save_every_n_epochs=1 + --mixed_precision="fp16" + --gradient_checkpointing +``` + +In reality, you need to write this in a single line, but it's shown with line breaks for readability (on Linux or Mac, you can add `\` at the end of each line to break lines). For Windows, either write it in a single line without breaks or add `^` at the end of each line. + +Next, we'll explain the main command-line arguments. + +
+日本語 + +学習は、ターミナルから `train_network.py` を実行することで開始します。実行時には、学習に関する様々な設定をコマンドライン引数として指定します。 + +以下に、基本的なコマンドライン実行例を示します。 + +実際には1行で書く必要がありますが、見やすさのために改行しています(Linux や Mac では `\` を行末に追加することで改行できます)。Windows の場合は、改行せずに1行で書くか、`^` を行末に追加してください。 + +次に、主要なコマンドライン引数について解説します。 +
+ +### 3.1. Main Command-Line Arguments / 主要なコマンドライン引数 + +#### Model Related / モデル関連 + +* `--pretrained_model_name_or_path=""` **[Required]** + * Specifies the Stable Diffusion model to be used as the base for training. You can specify the path to a local `.ckpt` or `.safetensors` file, or a directory containing a Diffusers format model. You can also specify a Hugging Face Hub model ID (e.g., `"stabilityai/stable-diffusion-2-1-base"`). +* `--v2` + * Specify this when the base model is Stable Diffusion v2.x. +* `--v_parameterization` + * Specify this when training with a v-prediction model (such as v2.x 768px models). + +#### Dataset Related / データセット関連 + +* `--dataset_config=""` + * Specifies the path to a `.toml` file describing the dataset configuration. (For details on dataset configuration, see [here](link/to/dataset/config/doc)) + * It's also possible to specify dataset settings from the command line, but using a `.toml` file is recommended as it becomes lengthy. + +#### Output and Save Related / 出力・保存関連 + +* `--output_dir=""` **[Required]** + * Specifies the directory where trained LoRA models, sample images, logs, etc. will be output. +* `--output_name=""` **[Required]** + * Specifies the filename of the trained LoRA model (excluding the extension). +* `--save_model_as="safetensors"` + * Specifies the format for saving the model. You can choose from `safetensors` (recommended), `ckpt`, or `pt`. The default is `safetensors`. +* `--save_every_n_epochs=1` + * Saves the model every specified number of epochs. If not specified, only the final model will be saved. +* `--save_every_n_steps=1000` + * Saves the model every specified number of steps. If both epoch and step saving are specified, both will be saved. + +#### LoRA Parameters / LoRA パラメータ + +* `--network_module=networks.lora` **[Required]** + * Specifies the type of network to train. For LoRA, specify `networks.lora`. +* `--network_dim=16` **[Required]** + * Specifies the rank (dimension) of LoRA. Higher values increase expressiveness but also increase file size and computational cost. Values between 4 and 128 are commonly used. There is no default (module dependent). +* `--network_alpha=1` + * Specifies the alpha value for LoRA. This parameter is related to learning rate scaling. It is generally recommended to set it to about half the value of `network_dim`, but it can also be the same value as `network_dim`. The default is 1. Setting it to the same value as `network_dim` will result in behavior similar to older versions. + +#### Training Parameters / 学習パラメータ + +* `--learning_rate=1e-4` + * Specifies the learning rate. For LoRA training (when alpha value is 1), relatively higher values (e.g., from `1e-4` to `1e-3`) are often used. +* `--unet_lr=1e-4` + * Used to specify a separate learning rate for the LoRA modules in the U-Net part. If not specified, the value of `--learning_rate` is used. +* `--text_encoder_lr=1e-5` + * Used to specify a separate learning rate for the LoRA modules in the Text Encoder part. If not specified, the value of `--learning_rate` is used. A smaller value than that for U-Net is recommended. +* `--optimizer_type="AdamW8bit"` + * Specifies the optimizer to use for training. Options include `AdamW8bit` (requires `bitsandbytes`), `AdamW`, `Lion` (requires `lion-pytorch`), `DAdaptation` (requires `dadaptation`), and `Adafactor`. `AdamW8bit` is memory-efficient and widely used. +* `--lr_scheduler="constant"` + * Specifies the learning rate scheduler. This is the method for changing the learning rate as training progresses. Options include `constant` (no change), `cosine` (cosine curve), `linear` (linear decay), `constant_with_warmup` (constant with warmup), and `cosine_with_restarts`. `constant`, `cosine`, and `constant_with_warmup` are commonly used. +* `--lr_warmup_steps=500` + * Specifies the number of warmup steps for the learning rate scheduler. This is the period during which the learning rate gradually increases at the start of training. Valid when the `lr_scheduler` supports warmup. +* `--max_train_steps=10000` + * Specifies the total number of training steps. If `max_train_epochs` is specified, that takes precedence. +* `--max_train_epochs=12` + * Specifies the number of training epochs. If this is specified, `max_train_steps` is ignored. +* `--sdpa` + * Uses Scaled Dot-Product Attention. This can reduce memory usage and improve training speed for LoRA training. +* `--mixed_precision="fp16"` + * Specifies the mixed precision training setting. Options are `no` (disabled), `fp16` (half precision), and `bf16` (bfloat16). If your GPU supports it, specifying `fp16` or `bf16` can improve training speed and reduce memory usage. +* `--gradient_accumulation_steps=1` + * Specifies the number of steps to accumulate gradients. This effectively increases the batch size to `train_batch_size * gradient_accumulation_steps`. Set a larger value if GPU memory is insufficient. Usually `1` is fine. + +#### Others / その他 + +* `--seed=42` + * Specifies the random seed. Set this if you want to ensure reproducibility of the training. +* `--logging_dir=""` + * Specifies the directory to output logs for TensorBoard, etc. If not specified, logs will not be output. +* `--log_prefix=""` + * Specifies the prefix for the subdirectory name created within `logging_dir`. +* `--gradient_checkpointing` + * Enables Gradient Checkpointing. This can significantly reduce memory usage but slightly decreases training speed. Useful when memory is limited. +* `--clip_skip=1` + * Specifies how many layers to skip from the last layer of the Text Encoder. Specifying `2` will use the output from the second-to-last layer. `None` or `1` means no skip (uses the last layer). Check the recommended value for the model you are training. + +
+日本語 + +#### モデル関連 + +* `--pretrained_model_name_or_path="<モデルのパス>"` **[必須]** + * 学習のベースとなる Stable Diffusion モデルを指定します。ローカルの `.ckpt` または `.safetensors` ファイルのパス、あるいは Diffusers 形式モデルのディレクトリを指定できます。Hugging Face Hub のモデル ID (例: `"stabilityai/stable-diffusion-2-1-base"`) も指定可能です。 +* `--v2` + * ベースモデルが Stable Diffusion v2.x の場合に指定します。 +* `--v_parameterization` + * v-prediction モデル(v2.x の 768px モデルなど)で学習する場合に指定します。 + +#### データセット関連 + +* `--dataset_config="<設定ファイルのパス>"` + * データセット設定を記述した `.toml` ファイルのパスを指定します。(データセット設定の詳細は[こちら](link/to/dataset/config/doc)) + * コマンドラインからデータセット設定を指定することも可能ですが、長くなるため `.toml` ファイルを使用することを推奨します。 + +#### 出力・保存関連 + +* `--output_dir="<出力先ディレクトリ>"` **[必須]** + * 学習済み LoRA モデルやサンプル画像、ログなどが出力されるディレクトリを指定します。 +* `--output_name="<出力ファイル名>"` **[必須]** + * 学習済み LoRA モデルのファイル名(拡張子を除く)を指定します。 +* `--save_model_as="safetensors"` + * モデルの保存形式を指定します。`safetensors` (推奨), `ckpt`, `pt` から選択できます。デフォルトは `safetensors` です。 +* `--save_every_n_epochs=1` + * 指定したエポックごとにモデルを保存します。省略するとエポックごとの保存は行われません(最終モデルのみ保存)。 +* `--save_every_n_steps=1000` + * 指定したステップごとにモデルを保存します。エポック指定 (`save_every_n_epochs`) と同時に指定された場合、両方とも保存されます。 + +#### LoRA パラメータ + +* `--network_module=networks.lora` **[必須]** + * 学習するネットワークの種別を指定します。LoRA の場合は `networks.lora` を指定します。 +* `--network_dim=16` **[必須]** + * LoRA のランク (rank / 次元数) を指定します。値が大きいほど表現力は増しますが、ファイルサイズと計算コストが増加します。一般的には 4〜128 程度の値が使われます。デフォルトは指定されていません(モジュール依存)。 +* `--network_alpha=1` + * LoRA のアルファ値 (alpha) を指定します。学習率のスケーリングに関係するパラメータで、一般的には `network_dim` の半分程度の値を指定することが推奨されますが、`network_dim` と同じ値を指定する場合もあります。デフォルトは 1 です。`network_dim` と同じ値に設定すると、旧バージョンと同様の挙動になります。 + +#### 学習パラメータ + +* `--learning_rate=1e-4` + * 学習率を指定します。LoRA 学習では(アルファ値が1の場合)比較的高めの値(例: `1e-4`から`1e-3`)が使われることが多いです。 +* `--unet_lr=1e-4` + * U-Net 部分の LoRA モジュールに対する学習率を個別に指定する場合に使用します。指定しない場合は `--learning_rate` の値が使用されます。 +* `--text_encoder_lr=1e-5` + * Text Encoder 部分の LoRA モジュールに対する学習率を個別に指定する場合に使用します。指定しない場合は `--learning_rate` の値が使用されます。U-Net よりも小さめの値が推奨されます。 +* `--optimizer_type="AdamW8bit"` + * 学習に使用するオプティマイザを指定します。`AdamW8bit` (要 `bitsandbytes`), `AdamW`, `Lion` (要 `lion-pytorch`), `DAdaptation` (要 `dadaptation`), `Adafactor` などが選択可能です。`AdamW8bit` はメモリ効率が良く、広く使われています。 +* `--lr_scheduler="constant"` + * 学習率スケジューラを指定します。学習の進行に合わせて学習率を変化させる方法です。`constant` (変化なし), `cosine` (コサインカーブ), `linear` (線形減衰), `constant_with_warmup` (ウォームアップ付き定数), `cosine_with_restarts` などが選択可能です。`constant`や`cosine` 、 `constant_with_warmup` がよく使われます。 +* `--lr_warmup_steps=500` + * 学習率スケジューラのウォームアップステップ数を指定します。学習開始時に学習率を徐々に上げていく期間です。`lr_scheduler` がウォームアップをサポートする場合に有効です。 +* `--max_train_steps=10000` + * 学習の総ステップ数を指定します。`max_train_epochs` が指定されている場合はそちらが優先されます。 +* `--max_train_epochs=12` + * 学習のエポック数を指定します。これを指定すると `max_train_steps` は無視されます。 +* `--sdpa` + * Scaled Dot-Product Attention を使用します。LoRA の学習において、メモリ使用量を削減し、学習速度を向上させることができます。 +* `--mixed_precision="fp16"` + * 混合精度学習の設定を指定します。`no` (無効), `fp16` (半精度), `bf16` (bfloat16) から選択できます。GPU が対応している場合は `fp16` または `bf16` を指定することで、学習速度の向上とメモリ使用量の削減が期待できます。 +* `--gradient_accumulation_steps=1` + * 勾配を累積するステップ数を指定します。実質的なバッチサイズを `train_batch_size * gradient_accumulation_steps` に増やす効果があります。GPU メモリが足りない場合に大きな値を設定します。通常は `1` で問題ありません。 + +#### その他 + +* `--seed=42` + * 乱数シードを指定します。学習の再現性を確保したい場合に設定します。 +* `--logging_dir="<ログディレクトリ>"` + * TensorBoard などのログを出力するディレクトリを指定します。指定しない場合、ログは出力されません。 +* `--log_prefix="<プレフィックス>"` + * `logging_dir` 内に作成されるサブディレクトリ名の接頭辞を指定します。 +* `--gradient_checkpointing` + * Gradient Checkpointing を有効にします。メモリ使用量を大幅に削減できますが、学習速度は若干低下します。メモリが厳しい場合に有効です。 +* `--clip_skip=1` + * Text Encoder の最後の層から数えて何層スキップするかを指定します。`2` を指定すると最後から 2 層目の出力を使用します。`None` または `1` はスキップなし(最後の層を使用)を意味します。学習対象のモデルの推奨する値を確認してください。 +
+ +### 3.2. Starting the Training / 学習の開始 + +After setting the necessary arguments and executing the command, training will begin. The progress of the training will be output to the console. If `logging_dir` is specified, you can visually check the training status (loss, learning rate, etc.) with TensorBoard. + +```bash +tensorboard --logdir +``` + +
+日本語 + +必要な引数を設定し、コマンドを実行すると学習が開始されます。学習の進行状況はコンソールに出力されます。`logging_dir` を指定した場合は、TensorBoard などで学習状況(損失や学習率など)を視覚的に確認できます。 +
+ +## 4. Using the Trained Model / 学習済みモデルの利用 + +Once training is complete, a LoRA model file (`.safetensors` or `.ckpt`) with the name specified by `output_name` will be saved in the directory specified by `output_dir`. + +This file can be used with GUI tools such as AUTOMATIC1111/stable-diffusion-webui, ComfyUI, etc. + +
+日本語 + +学習が完了すると、`output_dir` で指定したディレクトリに、`output_name` で指定した名前の LoRA モデルファイル (`.safetensors` または `.ckpt`) が保存されます。 + +このファイルは、AUTOMATIC1111/stable-diffusion-webui 、ComfyUI などの GUI ツールで利用できます。 +
+ +## 5. Other Features / その他の機能 + +`train_network.py` has many other options not introduced here. + +* Sample image generation (`--sample_prompts`, `--sample_every_n_steps`, etc.) +* More detailed optimizer settings (`--optimizer_args`, etc.) +* Caption preprocessing (`--shuffle_caption`, `--keep_tokens`, etc.) +* Additional network settings (`--network_args`, etc.) + +For these features, please refer to the script's help (`python train_network.py --help`) or other documents in the repository. + +
+日本語 + +`train_network.py` には、ここで紹介した以外にも多くのオプションがあります。 + +* サンプル画像の生成 (`--sample_prompts`, `--sample_every_n_steps` など) +* より詳細なオプティマイザ設定 (`--optimizer_args` など) +* キャプションの前処理 (`--shuffle_caption`, `--keep_tokens` など) +* ネットワークの追加設定 (`--network_args` など) + +これらの機能については、スクリプトのヘルプ (`python train_network.py --help`) やリポジトリ内の他のドキュメントを参照してください。 +
\ No newline at end of file From ceb19bebf849df1d9d6d5928eba777c95bfda8c4 Mon Sep 17 00:00:00 2001 From: Kohya S Date: Sun, 13 Apr 2025 22:06:58 +0900 Subject: [PATCH 2/9] update docs. sdxl is transltaed, flux.1 is corrected --- docs/flux_train_network.md | 224 ++++++++++++++++++++++++++++++++++--- docs/sd3_train_network.md | 8 +- docs/sdxl_train_network.md | 195 +++++++++++++++++++++++++++++--- 3 files changed, 388 insertions(+), 39 deletions(-) diff --git a/docs/flux_train_network.md b/docs/flux_train_network.md index d28d5877..46eee3e7 100644 --- a/docs/flux_train_network.md +++ b/docs/flux_train_network.md @@ -6,7 +6,7 @@ `flux_train_network.py`は、FLUX.1モデルに対してLoRAなどの追加ネットワークを学習させるためのスクリプトです。FLUX.1はStable Diffusionとは異なるアーキテクチャを持つ画像生成モデルであり、このスクリプトを使用することで、特定のキャラクターや画風を再現するLoRAモデルを作成できます。 -このガイドは、基本的なLoRA学習の手順を理解しているユーザーを対象とし、`train_network.py`での学習経験があることを前提としています。基本的な使い方や共通のオプションについては、[`train_network.py`のガイド](how_to_use_train_network.md)を参照してください。 +このガイドは、基本的なLoRA学習の手順を理解しているユーザーを対象としています。基本的な使い方や共通のオプションについては、[`train_network.py`のガイド](train_network.md)を参照してください。また一部のパラメータは [`sdxl_train_network.py`](sdxl_train_network.md) と同様のものがあるため、そちらも参考にしてください。 **前提条件:** @@ -30,9 +30,9 @@ 1. **学習スクリプト:** `flux_train_network.py` 2. **FLUX.1モデルファイル:** 学習のベースとなるFLUX.1モデルの`.safetensors`ファイル(例: `flux1-dev.safetensors`)。 3. **Text Encoderモデルファイル:** - * CLIP-Lモデルの`.safetensors`ファイル。 - * T5-XXLモデルの`.safetensors`ファイル。 -4. **AutoEncoderモデルファイル:** FLUX.1に対応するAEモデルの`.safetensors`ファイル。 + * CLIP-Lモデルの`.safetensors`ファイル。例として`clip_l.safetensors`を使用します。 + * T5-XXLモデルの`.safetensors`ファイル。例として`t5xxl.safetensors`を使用します。 +4. **AutoEncoderモデルファイル:** FLUX.1に対応するAEモデルの`.safetensors`ファイル。例として`ae.safetensors`を使用します。 5. **データセット定義ファイル (.toml):** 学習データセットの設定を記述したTOML形式のファイル。(詳細は[データセット設定ガイド](link/to/dataset/config/doc)を参照してください)。 * 例として`my_flux_dataset_config.toml`を使用します。 @@ -53,7 +53,7 @@ accelerate launch --num_cpu_threads_per_process 1 flux_train_network.py --output_dir="" --output_name="my_flux_lora" --save_model_as=safetensors - --network_module=networks.lora + --network_module=networks.lora_flux --network_dim=16 --network_alpha=1 --learning_rate=1e-4 @@ -64,15 +64,18 @@ accelerate launch --num_cpu_threads_per_process 1 flux_train_network.py --save_every_n_epochs=1 --mixed_precision="fp16" --gradient_checkpointing - --apply_t5_attn_mask + --guidance_scale=1.0 + --timestep_sampling="flux_shift" --blocks_to_swap=18 + --cache_text_encoder_outputs + --cache_latents ``` ※実際には1行で書くか、適切な改行文字(`\` または `^`)を使用してください。 ### 4.1. 主要なコマンドライン引数の解説(`train_network.py`からの追加・変更点) -[`train_network.py`のガイド](how_to_use_train_network.md)で説明されている引数に加え、以下のFLUX.1特有の引数を指定します。共通の引数(`--output_dir`, `--output_name`, `--network_module`, `--network_dim`, `--network_alpha`, `--learning_rate`など)については、上記ガイドを参照してください。 +[`train_network.py`のガイド](train_network.md)で説明されている引数に加え、以下のFLUX.1特有の引数を指定します。共通の引数(`--output_dir`, `--output_name`, `--network_module`, `--network_dim`, `--network_alpha`, `--learning_rate`など)については、上記ガイドを参照してください。 #### モデル関連 [必須] @@ -87,26 +90,26 @@ accelerate launch --num_cpu_threads_per_process 1 flux_train_network.py #### FLUX.1 学習パラメータ -* `--t5xxl_max_token_length=` - * T5-XXL Text Encoderで使用するトークンの最大長を指定します。省略した場合、モデルがschnell版なら256、dev版なら512が自動的に設定されます。データセットのキャプション長に合わせて調整が必要な場合があります。 -* `--apply_t5_attn_mask` - * T5-XXLの出力とFLUXモデル内部(Double Block)のアテンション計算時に、パディングトークンに対応するアテンションマスクを適用します。精度向上が期待できる場合がありますが、わずかに計算コストが増加します。 * `--guidance_scale=` - * FLUX.1 dev版は特定のガイダンススケール値で蒸留されているため、学習時にもその値を指定します。デフォルトは`3.5`です。schnell版では通常無視されます。 + * FLUX.1 dev版は特定のガイダンススケール値で蒸留されていますが、学習時には `1.0` を指定してガイダンススケールを無効化します。デフォルトは`3.5`ですので、必ず指定してください。schnell版では通常無視されます。 * `--timestep_sampling=` - * 学習時に使用するタイムステップ(ノイズレベル)のサンプリング方法を指定します。`sigma`, `uniform`, `sigmoid`, `shift`, `flux_shift` から選択します。デフォルトは `sigma` です。 + * 学習時に使用するタイムステップ(ノイズレベル)のサンプリング方法を指定します。`sigma`, `uniform`, `sigmoid`, `shift`, `flux_shift` から選択します。デフォルトは `sigma` です。推奨は `flux_shift` です。 * `--sigmoid_scale=` - * `timestep_sampling` に `sigmoid` または `shift`, `flux_shift` を指定した場合のスケール係数です。デフォルトは`1.0`です。 + * `timestep_sampling` に `sigmoid` または `shift`, `flux_shift` を指定した場合のスケール係数です。デフォルトおよび推奨値は`1.0`です。 * `--model_prediction_type=` - * モデルが何を予測するかを指定します。`raw` (予測値をそのまま使用), `additive` (ノイズ入力に加算), `sigma_scaled` (シグマスケーリングを適用) から選択します。デフォルトは `sigma_scaled` です。 + * モデルが何を予測するかを指定します。`raw` (予測値をそのまま使用), `additive` (ノイズ入力に加算), `sigma_scaled` (シグマスケーリングを適用) から選択します。デフォルトは `sigma_scaled` です。推奨は `raw` です。 * `--discrete_flow_shift=` - * Flow Matchingで使用されるスケジューラのシフト値を指定します。デフォルトは`3.0`です。 + * Flow Matchingで使用されるスケジューラのシフト値を指定します。デフォルトは`3.0`です。`timestep_sampling`に`flux_shift`を指定した場合は、この値は無視されます。 #### メモリ・速度関連 * `--blocks_to_swap=` **[実験的機能]** * VRAM使用量を削減するために、モデルの一部(Transformerブロック)をCPUとGPU間でスワップする設定です。スワップするブロック数を整数で指定します(例: `18`)。値を大きくするとVRAM使用量は減りますが、学習速度は低下します。GPUのVRAM容量に応じて調整してください。`gradient_checkpointing`と併用可能です。 * `--cpu_offload_checkpointing`とは併用できません。 +* `--cache_text_encoder_outputs` + * CLIP-LおよびT5-XXLの出力をキャッシュします。これにより、メモリ使用量が削減されます。 +* `--cache_latents`, `--cache_latents_to_disk` + * AEの出力をキャッシュします。[sdxl_train_network.py](sdxl_train_network.md)と同様の機能です。 #### 非互換・非推奨の引数 @@ -116,7 +119,7 @@ accelerate launch --num_cpu_threads_per_process 1 flux_train_network.py ### 4.2. 学習の開始 -必要な引数を設定し、コマンドを実行すると学習が開始されます。基本的な流れやログの確認方法は[`train_network.py`のガイド](how_to_use_train_network.md#32-starting-the-training--学習の開始)と同様です。 +必要な引数を設定し、コマンドを実行すると学習が開始されます。基本的な流れやログの確認方法は[`train_network.py`のガイド](train_network.md#32-starting-the-training--学習の開始)と同様です。 ## 5. 学習済みモデルの利用 @@ -124,4 +127,189 @@ accelerate launch --num_cpu_threads_per_process 1 flux_train_network.py ## 6. その他 -`flux_train_network.py`には、サンプル画像の生成 (`--sample_prompts`など) や詳細なオプティマイザ設定など、`train_network.py`と共通の機能も多く存在します。これらについては、[`train_network.py`のガイド](how_to_use_train_network.md#5-other-features--その他の機能)やスクリプトのヘルプ (`python flux_train_network.py --help`) を参照してください。 +`flux_train_network.py`には、サンプル画像の生成 (`--sample_prompts`など) や詳細なオプティマイザ設定など、`train_network.py`と共通の機能も多く存在します。これらについては、[`train_network.py`のガイド](train_network.md#5-other-features--その他の機能)やスクリプトのヘルプ (`python flux_train_network.py --help`) を参照してください。 + +# FLUX.1 LoRA学習の補足説明 + +以下は、以上の基本的なFLUX.1 LoRAの学習手順を補足するものです。より詳細な設定オプションなどについて説明します。 + +## 1. VRAM使用量の最適化 + +FLUX.1モデルは比較的大きなモデルであるため、十分なVRAMを持たないGPUでは工夫が必要です。以下に、VRAM使用量を削減するための設定を紹介します。 + +### 1.1 メモリ使用量別の推奨設定 + +| GPUメモリ | 推奨設定 | +|----------|----------| +| 24GB VRAM | 基本設定で問題なく動作します(バッチサイズ2) | +| 16GB VRAM | バッチサイズ1に設定し、`--blocks_to_swap`を使用 | +| 12GB VRAM | `--blocks_to_swap 16`と8bit AdamWを使用 | +| 10GB VRAM | `--blocks_to_swap 22`を使用、T5XXLはfp8形式を推奨 | +| 8GB VRAM | `--blocks_to_swap 28`を使用、T5XXLはfp8形式を推奨 | + +### 1.2 主要なVRAM削減オプション + +- **`--blocks_to_swap <数値>`**: + CPUとGPU間でブロックをスワップしてVRAM使用量を削減します。数値が大きいほど多くのブロックをスワップし、より多くのVRAMを節約できますが、学習速度は低下します。FLUX.1では最大35ブロックまでスワップ可能です。 + +- **`--cpu_offload_checkpointing`**: + 勾配チェックポイントをCPUにオフロードします。これにより最大1GBのVRAM使用量を削減できますが、学習速度は約15%低下します。`--blocks_to_swap`とは併用できません。 + +- **`--cache_text_encoder_outputs` / `--cache_text_encoder_outputs_to_disk`**: + CLIP-LとT5-XXLの出力をキャッシュします。これによりメモリ使用量を削減できます。 + +- **`--cache_latents` / `--cache_latents_to_disk`**: + AEの出力をキャッシュします。メモリ使用量を削減できます。 + +- **Adafactor オプティマイザの使用**: + 8bit AdamWよりもVRAM使用量を削減できます。以下の設定を使用してください: + ``` + --optimizer_type adafactor --optimizer_args "relative_step=False" "scale_parameter=False" "warmup_init=False" --lr_scheduler constant_with_warmup --max_grad_norm 0.0 + ``` + +- **T5XXLのfp8形式の使用**: + 10GB未満のVRAMを持つGPUでは、T5XXLのfp8形式チェックポイントの使用を推奨します。[comfyanonymous/flux_text_encoders](https://huggingface.co/comfyanonymous/flux_text_encoders)から`t5xxl_fp8_e4m3fn.safetensors`をダウンロードできます(`scaled`なしで使用してください)。 + +## 2. FLUX.1 LoRA学習の重要な設定オプション + +FLUX.1の学習には多くの未知の点があり、いくつかの設定は引数で指定できます。以下に重要な引数とその説明を示します。 + +### 2.1 タイムステップのサンプリング方法 + +`--timestep_sampling`オプションで、タイムステップ(0-1)のサンプリング方法を指定できます: + +- `sigma`:SD3と同様のシグマベース +- `uniform`:一様ランダム +- `sigmoid`:正規分布乱数のシグモイド(x-flux、AI-toolkitなどと同様) +- `shift`:正規分布乱数のシグモイド値をシフト +- `flux_shift`:解像度に応じて正規分布乱数のシグモイド値をシフト(FLUX.1 dev推論と同様)。この設定では`--discrete_flow_shift`は無視されます。 + +### 2.2 モデル予測の処理方法 + +`--model_prediction_type`オプションで、モデルの予測をどのように解釈し処理するかを指定できます: + +- `raw`:そのまま使用(x-fluxと同様)【推奨】 +- `additive`:ノイズ入力に加算 +- `sigma_scaled`:シグマスケーリングを適用(SD3と同様) + +### 2.3 推奨設定 + +実験の結果、以下の設定が良好に動作することが確認されています: +``` +--timestep_sampling shift --discrete_flow_shift 3.1582 --model_prediction_type raw --guidance_scale 1.0 +``` + +ガイダンススケールについて:FLUX.1 dev版は特定のガイダンススケール値で蒸留されていますが、学習時には`--guidance_scale 1.0`を指定してガイダンススケールを無効化することを推奨します。 + +## 3. 各層に対するランク指定 + +FLUX.1の各層に対して異なるランク(network_dim)を指定できます。これにより、特定の層に対してLoRAの効果を強調したり、無効化したりできます。 + +以下のnetwork_argsを指定することで、各層のランクを指定できます。0を指定するとその層にはLoRAが適用されません。 + +| network_args | 対象レイヤー | +|--------------|--------------| +| img_attn_dim | DoubleStreamBlockのimg_attn | +| txt_attn_dim | DoubleStreamBlockのtxt_attn | +| img_mlp_dim | DoubleStreamBlockのimg_mlp | +| txt_mlp_dim | DoubleStreamBlockのtxt_mlp | +| img_mod_dim | DoubleStreamBlockのimg_mod | +| txt_mod_dim | DoubleStreamBlockのtxt_mod | +| single_dim | SingleStreamBlockのlinear1とlinear2 | +| single_mod_dim | SingleStreamBlockのmodulation | + +使用例: +``` +--network_args "img_attn_dim=4" "img_mlp_dim=8" "txt_attn_dim=2" "txt_mlp_dim=2" "img_mod_dim=2" "txt_mod_dim=2" "single_dim=4" "single_mod_dim=2" +``` + +さらに、FLUXの条件付けレイヤーにLoRAを適用するには、network_argsに`in_dims`を指定します。5つの数値をカンマ区切りのリストとして指定する必要があります。 + +例: +``` +--network_args "in_dims=[4,2,2,2,4]" +``` + +各数値は、`img_in`、`time_in`、`vector_in`、`guidance_in`、`txt_in`に対応します。上記の例では、すべての条件付けレイヤーにLoRAを適用し、`img_in`と`txt_in`のランクを4、その他のランクを2に設定しています。 + +0を指定するとそのレイヤーにはLoRAが適用されません。例えば、`[4,0,0,0,4]`は`img_in`と`txt_in`にのみLoRAを適用します。 + +## 4. 学習するブロックの指定 + +FLUX.1 LoRA学習では、network_argsの`train_double_block_indices`と`train_single_block_indices`を指定することで、学習するブロックを指定できます。インデックスは0ベースです。省略した場合のデフォルトはすべてのブロックを学習することです。 + +インデックスは、`0,1,5,8`のような整数のリストや、`0,1,4-5,7`のような整数の範囲として指定します。 +- double blocksの数は19なので、有効な範囲は0-18です +- single blocksの数は38なので、有効な範囲は0-37です +- `all`を指定するとすべてのブロックを学習します +- `none`を指定するとブロックを学習しません + +使用例: +``` +--network_args "train_double_block_indices=0,1,8-12,18" "train_single_block_indices=3,10,20-25,37" +``` + +または: +``` +--network_args "train_double_block_indices=none" "train_single_block_indices=10-15" +``` + +`train_double_block_indices`または`train_single_block_indices`のどちらか一方だけを指定した場合、もう一方は通常通り学習されます。 + +## 5. Text Encoder LoRAのサポート + +FLUX.1 LoRA学習は、CLIP-LとT5XXL LoRAのトレーニングもサポートしています。 + +- FLUX.1のみをトレーニングする場合は、`--network_train_unet_only`を指定します +- FLUX.1とCLIP-Lをトレーニングする場合は、`--network_train_unet_only`を省略します +- FLUX.1、CLIP-L、T5XXLすべてをトレーニングする場合は、`--network_train_unet_only`を省略し、`--network_args "train_t5xxl=True"`を追加します + +CLIP-LとT5XXLの学習率は、`--text_encoder_lr`で個別に指定できます。例えば、`--text_encoder_lr 1e-4 1e-5`とすると、最初の値はCLIP-Lの学習率、2番目の値はT5XXLの学習率になります。1つだけ指定すると、CLIP-LとT5XXLの学習率は同じになります。`--text_encoder_lr`を指定しない場合、デフォルトの学習率`--learning_rate`が両方に使用されます。 + +## 6. マルチ解像度トレーニング + +データセット設定ファイルで複数の解像度を定義できます。各解像度に対して異なるバッチサイズを指定することができます。 + +設定ファイルの例: +```toml +[general] +# 共通設定をここで定義 +flip_aug = true +color_aug = false +keep_tokens_separator= "|||" +shuffle_caption = false +caption_tag_dropout_rate = 0 +caption_extension = ".txt" + +[[datasets]] +# 最初の解像度の設定 +batch_size = 2 +enable_bucket = true +resolution = [1024, 1024] + + [[datasets.subsets]] + image_dir = "画像ディレクトリへのパス" + num_repeats = 1 + +[[datasets]] +# 2番目の解像度の設定 +batch_size = 3 +enable_bucket = true +resolution = [768, 768] + + [[datasets.subsets]] + image_dir = "画像ディレクトリへのパス" + num_repeats = 1 + +[[datasets]] +# 3番目の解像度の設定 +batch_size = 4 +enable_bucket = true +resolution = [512, 512] + + [[datasets.subsets]] + image_dir = "画像ディレクトリへのパス" + num_repeats = 1 +``` + +各解像度セクションの`[[datasets.subsets]]`部分は、データセットディレクトリを定義します。各解像度に対して同じディレクトリを指定してください。 \ No newline at end of file diff --git a/docs/sd3_train_network.md b/docs/sd3_train_network.md index d5cc5a75..a5b7a82f 100644 --- a/docs/sd3_train_network.md +++ b/docs/sd3_train_network.md @@ -6,7 +6,7 @@ `sd3_train_network.py`は、Stable Diffusion 3/3.5モデルに対してLoRAなどの追加ネットワークを学習させるためのスクリプトです。SD3は、MMDiT (Multi-Modal Diffusion Transformer) と呼ばれる新しいアーキテクチャを採用しており、従来のStable Diffusionモデルとは構造が異なります。このスクリプトを使用することで、SD3/3.5モデルに特化したLoRAモデルを作成できます。 -このガイドは、基本的なLoRA学習の手順を理解しているユーザーを対象とし、`train_network.py`での学習経験があることを前提としています。基本的な使い方や共通のオプションについては、[`train_network.py`のガイド](how_to_use_train_network.md)を参照してください。 +このガイドは、基本的なLoRA学習の手順を理解しているユーザーを対象とし、`train_network.py`での学習経験があることを前提としています。基本的な使い方や共通のオプションについては、[`train_network.py`のガイド](train_network.md)を参照してください。 **前提条件:** @@ -68,7 +68,7 @@ accelerate launch --num_cpu_threads_per_process 1 sd3_train_network.py ### 4.1. 主要なコマンドライン引数の解説(`train_network.py`からの追加・変更点) -[`train_network.py`のガイド](how_to_use_train_network.md)で説明されている引数に加え、以下のSD3/3.5特有の引数を指定します。共通の引数(`--output_dir`, `--output_name`, `--network_module`, `--network_dim`, `--network_alpha`, `--learning_rate`など)については、上記ガイドを参照してください。 +[`train_network.py`のガイド](train_network.md)で説明されている引数に加え、以下のSD3/3.5特有の引数を指定します。共通の引数(`--output_dir`, `--output_name`, `--network_module`, `--network_dim`, `--network_alpha`, `--learning_rate`など)については、上記ガイドを参照してください。 #### モデル関連 @@ -111,7 +111,7 @@ accelerate launch --num_cpu_threads_per_process 1 sd3_train_network.py ### 4.2. 学習の開始 -必要な引数を設定し、コマンドを実行すると学習が開始されます。基本的な流れやログの確認方法は[`train_network.py`のガイド](how_to_use_train_network.md#32-starting-the-training--学習の開始)と同様です。 +必要な引数を設定し、コマンドを実行すると学習が開始されます。基本的な流れやログの確認方法は[`train_network.py`のガイド](train_network.md#32-starting-the-training--学習の開始)と同様です。 ## 5. 学習済みモデルの利用 @@ -119,4 +119,4 @@ accelerate launch --num_cpu_threads_per_process 1 sd3_train_network.py ## 6. その他 -`sd3_train_network.py`には、サンプル画像の生成 (`--sample_prompts`など) や詳細なオプティマイザ設定など、`train_network.py`と共通の機能も多く存在します。これらについては、[`train_network.py`のガイド](how_to_use_train_network.md#5-other-features--その他の機能)やスクリプトのヘルプ (`python sd3_train_network.py --help`) を参照してください。 +`sd3_train_network.py`には、サンプル画像の生成 (`--sample_prompts`など) や詳細なオプティマイザ設定など、`train_network.py`と共通の機能も多く存在します。これらについては、[`train_network.py`のガイド](train_network.md#5-other-features--その他の機能)やスクリプトのヘルプ (`python sd3_train_network.py --help`) を参照してください。 diff --git a/docs/sdxl_train_network.md b/docs/sdxl_train_network.md index 8a19f7ae..e1f6e9b9 100644 --- a/docs/sdxl_train_network.md +++ b/docs/sdxl_train_network.md @@ -1,14 +1,27 @@ -はい、承知いたしました。`sd-scripts` リポジトリに含まれる `sdxl_train_network.py` を使用した SDXL LoRA 学習に関するドキュメントを作成します。`how_to_use_train_network.md` との差分を中心に、初心者ユーザー向けに解説します。 +# How to Use the SDXL LoRA Training Script `sdxl_train_network.py` / SDXL LoRA学習スクリプト `sdxl_train_network.py` の使い方 ---- - -# SDXL LoRA学習スクリプト `sdxl_train_network.py` の使い方 +This document explains the basic procedure for training a LoRA (Low-Rank Adaptation) model for SDXL (Stable Diffusion XL) using `sdxl_train_network.py` included in the `sd-scripts` repository. +
+日本語 このドキュメントでは、`sd-scripts` リポジトリに含まれる `sdxl_train_network.py` を使用して、SDXL (Stable Diffusion XL) モデルに対する LoRA (Low-Rank Adaptation) モデルを学習する基本的な手順について解説します。 +
-## 1. はじめに +## 1. Introduction / はじめに -`sdxl_train_network.py` は、SDXL モデルに対して LoRA などの追加ネットワークを学習させるためのスクリプトです。基本的な使い方は `train_network.py` ([LoRA学習スクリプト `train_network.py` の使い方](how_to_use_train_network.md) 参照) と共通ですが、SDXL モデル特有の設定が必要となります。 +`sdxl_train_network.py` is a script for training additional networks such as LoRA for SDXL models. The basic usage is common with `train_network.py` (see [How to Use the LoRA Training Script `train_network.py`](train_network.md)), but SDXL model-specific settings are required. + +This guide focuses on SDXL LoRA training, explaining the main differences from `train_network.py` and SDXL-specific configuration items. + +**Prerequisites:** + +* You have cloned the `sd-scripts` repository and set up the Python environment. +* Your training dataset is ready. (Please refer to the [Dataset Preparation Guide](link/to/dataset/doc) for dataset preparation) +* You have read [How to Use the LoRA Training Script `train_network.py`](train_network.md). + +
+日本語 +`sdxl_train_network.py` は、SDXL モデルに対して LoRA などの追加ネットワークを学習させるためのスクリプトです。基本的な使い方は `train_network.py` ([LoRA学習スクリプト `train_network.py` の使い方](train_network.md) 参照) と共通ですが、SDXL モデル特有の設定が必要となります。 このガイドでは、SDXL LoRA 学習に焦点を当て、`train_network.py` との主な違いや SDXL 特有の設定項目を中心に説明します。 @@ -16,10 +29,26 @@ * `sd-scripts` リポジトリのクローンと Python 環境のセットアップが完了していること。 * 学習用データセットの準備が完了していること。(データセットの準備については[データセット準備ガイド](link/to/dataset/doc)を参照してください) -* [LoRA学習スクリプト `train_network.py` の使い方](how_to_use_train_network.md) を一読していること。 +* [LoRA学習スクリプト `train_network.py` の使い方](train_network.md) を一読していること。 +
-## 2. 準備 +## 2. Preparation / 準備 +Before starting training, you need the following files: + +1. **Training Script:** `sdxl_train_network.py` +2. **Dataset Definition File (.toml):** A TOML format file describing the training dataset configuration. + +### About the Dataset Definition File + +The basic format of the dataset definition file (`.toml`) is the same as for `train_network.py`. Please refer to the [Dataset Configuration Guide](link/to/dataset/config/doc) and [How to Use the LoRA Training Script `train_network.py`](train_network.md#about-the-dataset-definition-file). + +For SDXL, it is common to use high-resolution datasets and the aspect ratio bucketing feature (`enable_bucket = true`). + +In this example, we'll use a file named `my_sdxl_dataset_config.toml`. + +
+日本語 学習を開始する前に、以下のファイルが必要です。 1. **学習スクリプト:** `sdxl_train_network.py` @@ -27,14 +56,55 @@ ### データセット定義ファイルについて -データセット定義ファイル (`.toml`) の基本的な書き方は `train_network.py` と共通です。[データセット設定ガイド](link/to/dataset/config/doc) および [LoRA学習スクリプト `train_network.py` の使い方](how_to_use_train_network.md#データセット定義ファイルについて) を参照してください。 +データセット定義ファイル (`.toml`) の基本的な書き方は `train_network.py` と共通です。[データセット設定ガイド](link/to/dataset/config/doc) および [LoRA学習スクリプト `train_network.py` の使い方](train_network.md#データセット定義ファイルについて) を参照してください。 SDXL では、高解像度のデータセットや、アスペクト比バケツ機能 (`enable_bucket = true`) の利用が一般的です。 ここでは、例として `my_sdxl_dataset_config.toml` という名前のファイルを使用することにします。 +
-## 3. 学習の実行 +## 3. Running the Training / 学習の実行 +Training starts by running `sdxl_train_network.py` from the terminal. + +Here's a basic command line execution example for SDXL LoRA training: + +```bash +accelerate launch --num_cpu_threads_per_process 1 sdxl_train_network.py + --pretrained_model_name_or_path="" + --dataset_config="my_sdxl_dataset_config.toml" + --output_dir="" + --output_name="my_sdxl_lora" + --save_model_as=safetensors + --network_module=networks.lora + --network_dim=32 + --network_alpha=16 + --learning_rate=1e-4 + --unet_lr=1e-4 + --text_encoder_lr1=1e-5 + --text_encoder_lr2=1e-5 + --optimizer_type="AdamW8bit" + --lr_scheduler="constant" + --max_train_epochs=10 + --save_every_n_epochs=1 + --mixed_precision="bf16" + --gradient_checkpointing + --cache_text_encoder_outputs + --cache_latents +``` + +Comparing with the execution example of `train_network.py`, the following points are different: + +* The script to execute is `sdxl_train_network.py`. +* You specify an SDXL base model for `--pretrained_model_name_or_path`. +* `--text_encoder_lr` is split into `--text_encoder_lr1` and `--text_encoder_lr2` (since SDXL has two Text Encoders). +* `--mixed_precision` is recommended to be `bf16` or `fp16`. +* `--cache_text_encoder_outputs` and `--cache_latents` are recommended to reduce VRAM usage. + +Next, we'll explain the main command line arguments that differ from `train_network.py`. For common arguments, please refer to [How to Use the LoRA Training Script `train_network.py`](train_network.md#31-main-command-line-arguments). + +
+日本語 学習は、ターミナルから `sdxl_train_network.py` を実行することで開始します。 以下に、SDXL LoRA 学習における基本的なコマンドライン実行例を示します。 @@ -71,10 +141,78 @@ accelerate launch --num_cpu_threads_per_process 1 sdxl_train_network.py * `--mixed_precision` は `bf16` または `fp16` が推奨されます。 * `--cache_text_encoder_outputs` や `--cache_latents` は VRAM 使用量を削減するために推奨されます。 -次に、`train_network.py` との差分となる主要なコマンドライン引数について解説します。共通の引数については、[LoRA学習スクリプト `train_network.py` の使い方](how_to_use_train_network.md#31-主要なコマンドライン引数) を参照してください。 +次に、`train_network.py` との差分となる主要なコマンドライン引数について解説します。共通の引数については、[LoRA学習スクリプト `train_network.py` の使い方](train_network.md#31-主要なコマンドライン引数) を参照してください。 +
-### 3.1. 主要なコマンドライン引数(差分) +### 3.1. Main Command Line Arguments (Differences) / 主要なコマンドライン引数(差分) +#### Model Related / モデル関連 + +* `--pretrained_model_name_or_path=""` **[Required]** + * Specifies the **SDXL model** to be used as the base for training. You can specify a Hugging Face Hub model ID (e.g., `"stabilityai/stable-diffusion-xl-base-1.0"`), a local Diffusers format model directory, or a path to a `.safetensors` file. +* `--v2`, `--v_parameterization` + * These arguments are for SD1.x/2.x. When using `sdxl_train_network.py`, since an SDXL model is assumed, these **typically do not need to be specified**. + +#### Dataset Related / データセット関連 + +* `--dataset_config=""` + * This is common with `train_network.py`. + * For SDXL, it is common to use high-resolution data and the bucketing feature (specify `enable_bucket = true` in the `.toml` file). + +#### Output & Save Related / 出力・保存関連 + +* These are common with `train_network.py`. + +#### LoRA Parameters / LoRA パラメータ + +* These are common with `train_network.py`. + +#### Training Parameters / 学習パラメータ + +* `--learning_rate=1e-4` + * Overall learning rate. This becomes the default value if `unet_lr`, `text_encoder_lr1`, and `text_encoder_lr2` are not specified. +* `--unet_lr=1e-4` + * Learning rate for LoRA modules in the U-Net part. If not specified, the value of `--learning_rate` is used. +* `--text_encoder_lr1=1e-5` + * Learning rate for LoRA modules in **Text Encoder 1 (OpenCLIP ViT-G/14)**. If not specified, the value of `--learning_rate` is used. A smaller value than U-Net is recommended. +* `--text_encoder_lr2=1e-5` + * Learning rate for LoRA modules in **Text Encoder 2 (CLIP ViT-L/14)**. If not specified, the value of `--learning_rate` is used. A smaller value than U-Net is recommended. +* `--optimizer_type="AdamW8bit"` + * Common with `train_network.py`. +* `--lr_scheduler="constant"` + * Common with `train_network.py`. +* `--lr_warmup_steps` + * Common with `train_network.py`. +* `--max_train_steps`, `--max_train_epochs` + * Common with `train_network.py`. +* `--mixed_precision="bf16"` + * Mixed precision training setting. For SDXL, `bf16` or `fp16` is recommended. Choose the one supported by your GPU. This reduces VRAM usage and improves training speed. +* `--gradient_accumulation_steps=1` + * Common with `train_network.py`. +* `--gradient_checkpointing` + * Common with `train_network.py`. Recommended to enable for SDXL due to its high memory consumption. +* `--cache_latents` + * Caches VAE outputs in memory (or on disk when `--cache_latents_to_disk` is specified). By skipping VAE computation, this reduces VRAM usage and speeds up training. Image augmentations (`--color_aug`, `--flip_aug`, `--random_crop`, etc.) are disabled. This option is recommended for SDXL training. +* `--cache_latents_to_disk` + * Used with `--cache_latents`, caches to disk. When loading the dataset for the first time, VAE outputs are cached to disk. This is recommended when you have a large number of training images, as it allows you to skip VAE computation on subsequent training runs. +* `--cache_text_encoder_outputs` + * Caches Text Encoder outputs in memory (or on disk when `--cache_text_encoder_outputs_to_disk` is specified). By skipping Text Encoder computation, this reduces VRAM usage and speeds up training. Caption augmentations (`--shuffle_caption`, `--caption_dropout_rate`, etc.) are disabled. + * **Note:** When using this option, LoRA modules for Text Encoder cannot be trained (`--network_train_unet_only` must be specified). +* `--cache_text_encoder_outputs_to_disk` + * Used with `--cache_text_encoder_outputs`, caches to disk. +* `--no_half_vae` + * Runs VAE in `float32` even when using mixed precision (`fp16`/`bf16`). Since SDXL's VAE can be unstable in `float16`, enable this when using `fp16`. +* `--clip_skip` + * Not normally used for SDXL. No need to specify. +* `--fused_backward_pass` + * Fuses gradient computation and optimizer steps to reduce VRAM usage. Available for SDXL. (Currently only supports the `Adafactor` optimizer) + +#### Others / その他 + +* `--seed`, `--logging_dir`, `--log_prefix`, etc. are common with `train_network.py`. + +
+日本語 #### モデル関連 * `--pretrained_model_name_or_path="<モデルのパス>"` **[必須]** @@ -130,7 +268,7 @@ accelerate launch --num_cpu_threads_per_process 1 sdxl_train_network.py * `--cache_text_encoder_outputs_to_disk` * `--cache_text_encoder_outputs` と併用し、キャッシュ先をディスクにします。 * `--no_half_vae` - * 混合精度 (`fp16`/`bf16`) 使用時でも VAE を `float32` で動作させます。SDXL の VAE は `float16` で不安定になることがあるため、`fp16` 指定時には有効にしてくだ + * 混合精度 (`fp16`/`bf16`) 使用時でも VAE を `float32` で動作させます。SDXL の VAE は `float16` で不安定になることがあるため、`fp16` 指定時には有効にしてください。 * `--clip_skip` * SDXL では通常使用しません。指定は不要です。 * `--fused_backward_pass` @@ -139,22 +277,45 @@ accelerate launch --num_cpu_threads_per_process 1 sdxl_train_network.py #### その他 * `--seed`, `--logging_dir`, `--log_prefix` などは `train_network.py` と共通です。 +
-### 3.2. 学習の開始 +### 3.2. Starting the Training / 学習の開始 +After setting the necessary arguments, execute the command to start training. The training progress will be displayed on the console. The basic flow is the same as with `train_network.py`. + +
+日本語 必要な引数を設定し、コマンドを実行すると学習が開始されます。学習の進行状況はコンソールに出力されます。基本的な流れは `train_network.py` と同じです。 +
-## 4. 学習済みモデルの利用 +## 4. Using the Trained Model / 学習済みモデルの利用 +When training is complete, a LoRA model file (`.safetensors`, etc.) with the name specified by `output_name` will be saved in the directory specified by `output_dir`. + +This file can be used with GUI tools that support SDXL, such as AUTOMATIC1111/stable-diffusion-webui and ComfyUI. + +
+日本語 学習が完了すると、`output_dir` で指定したディレクトリに、`output_name` で指定した名前の LoRA モデルファイル (`.safetensors` など) が保存されます。 このファイルは、AUTOMATIC1111/stable-diffusion-webui 、ComfyUI などの SDXL に対応した GUI ツールで利用できます。 +
-## 5. 補足: `train_network.py` との主な違い +## 5. Supplement: Main Differences from `train_network.py` / 補足: `train_network.py` との主な違い +* **Target Model:** `sdxl_train_network.py` is exclusively for SDXL models. +* **Text Encoder:** Since SDXL has two Text Encoders, there are differences in learning rate specifications (`--text_encoder_lr1`, `--text_encoder_lr2`), etc. +* **Caching Features:** `--cache_text_encoder_outputs` is particularly effective for SDXL and is recommended. +* **Recommended Settings:** Due to high VRAM usage, mixed precision (`bf16` or `fp16`), `gradient_checkpointing`, and caching features (`--cache_latents`, `--cache_text_encoder_outputs`) are recommended. When using `fp16`, it is recommended to run the VAE in `float32` with `--no_half_vae`. + +For other detailed options, please refer to the script's help (`python sdxl_train_network.py --help`) and other documents in the repository. + +
+日本語 * **対象モデル:** `sdxl_train_network.py` は SDXL モデル専用です。 * **Text Encoder:** SDXL は 2 つの Text Encoder を持つため、学習率の指定 (`--text_encoder_lr1`, `--text_encoder_lr2`) などが異なります。 * **キャッシュ機能:** `--cache_text_encoder_outputs` は SDXL で特に効果が高く、推奨されます。 * **推奨設定:** VRAM 使用量が大きいため、`bf16` または `fp16` の混合精度、`gradient_checkpointing`、キャッシュ機能 (`--cache_latents`, `--cache_text_encoder_outputs`) の利用が推奨されます。`fp16` 指定時は、VAE は `--no_half_vae` で `float32` 動作を推奨します。 -その他の詳細なオプションについては、スクリプトのヘルプ (`python sdxl_train_network.py --help`) やリポジトリ内の他のドキュメントを参照してください。 \ No newline at end of file +その他の詳細なオプションについては、スクリプトのヘルプ (`python sdxl_train_network.py --help`) やリポジトリ内の他のドキュメントを参照してください。 +
\ No newline at end of file From b1bbd4576cd454073a0059c96555367af5f41d1f Mon Sep 17 00:00:00 2001 From: Kohya S Date: Mon, 14 Apr 2025 21:53:21 +0900 Subject: [PATCH 3/9] doc: update sd3 LoRA, sdxl LoRA advanced --- docs/sd3_train_network.md | 31 ++-- docs/sdxl_train_network_advanced.md | 260 ++++++++++++++++++++++++++++ 2 files changed, 276 insertions(+), 15 deletions(-) create mode 100644 docs/sdxl_train_network_advanced.md diff --git a/docs/sd3_train_network.md b/docs/sd3_train_network.md index a5b7a82f..95f7ce62 100644 --- a/docs/sd3_train_network.md +++ b/docs/sd3_train_network.md @@ -6,7 +6,7 @@ `sd3_train_network.py`は、Stable Diffusion 3/3.5モデルに対してLoRAなどの追加ネットワークを学習させるためのスクリプトです。SD3は、MMDiT (Multi-Modal Diffusion Transformer) と呼ばれる新しいアーキテクチャを採用しており、従来のStable Diffusionモデルとは構造が異なります。このスクリプトを使用することで、SD3/3.5モデルに特化したLoRAモデルを作成できます。 -このガイドは、基本的なLoRA学習の手順を理解しているユーザーを対象とし、`train_network.py`での学習経験があることを前提としています。基本的な使い方や共通のオプションについては、[`train_network.py`のガイド](train_network.md)を参照してください。 +このガイドは、基本的なLoRA学習の手順を理解しているユーザーを対象としています。基本的な使い方や共通のオプションについては、[`train_network.py`のガイド](train_network.md)を参照してください。また一部のパラメータは [`sdxl_train_network.py`](sdxl_train_network.md) と同様のものがあるため、そちらも参考にしてください。 **前提条件:** @@ -18,8 +18,8 @@ `sd3_train_network.py`は`train_network.py`をベースに、SD3/3.5モデルに対応するための変更が加えられています。主な違いは以下の通りです。 -* **対象モデル:** Stable Diffusion 3 Medium / Large (3.0 / 3.5) モデルを対象とします。 -* **モデル構造:** U-Netの代わりにMMDiT (Transformerベース) を使用します。Text EncoderとしてCLIP-L, CLIP-G, T5-XXLの三つを使用します。VAEはSDXLと互換性がありますが、入力のスケール処理が異なります。 +* **対象モデル:** Stable Diffusion 3, 3.5 Medium / Large モデルを対象とします。 +* **モデル構造:** U-Netの代わりにMMDiT (Transformerベース) を使用します。Text EncoderとしてCLIP-L, CLIP-G, T5-XXLの三つを使用します。VAEはSDXLと互換性がありません。 * **引数:** SD3/3.5モデル、Text Encoder群、VAEを指定する引数があります。ただし、単一ファイルの`.safetensors`形式であれば、内部で自動的に分離されるため、個別のパス指定は必須ではありません。 * **一部引数の非互換性:** Stable Diffusion v1/v2向けの引数(例: `--v2`, `--v_parameterization`, `--clip_skip`)はSD3/3.5の学習では使用されません。 * **SD3特有の引数:** Text Encoderのアテンションマスクやドロップアウト率、Positional Embeddingの調整(SD3.5向け)、タイムステップのサンプリングや損失の重み付けに関する引数が追加されています。 @@ -29,8 +29,8 @@ 学習を開始する前に、以下のファイルが必要です。 1. **学習スクリプト:** `sd3_train_network.py` -2. **SD3/3.5モデルファイル:** 学習のベースとなるSD3/3.5モデルの`.safetensors`ファイル。単一ファイル形式(Diffusers/ComfyUI/AUTOMATIC1111形式)を推奨します。 - * Text EncoderやVAEが別ファイルになっている場合は、対応する引数でパスを指定します。 +2. **SD3/3.5モデルファイル:** 学習のベースとなるSD3/3.5モデルの`.safetensors`ファイル。またText Encoderをそれぞれ対応する引数でパスを指定します。 + * 単一ファイル形式も使用可能です。 3. **データセット定義ファイル (.toml):** 学習データセットの設定を記述したTOML形式のファイル。(詳細は[データセット設定ガイド](link/to/dataset/config/doc)を参照してください)。 * 例として`my_sd3_dataset_config.toml`を使用します。 @@ -43,6 +43,9 @@ ```bash accelerate launch --num_cpu_threads_per_process 1 sd3_train_network.py --pretrained_model_name_or_path="" + --clip_l="" + --clip_g="" + --t5xxl="" --dataset_config="my_sd3_dataset_config.toml" --output_dir="" --output_name="my_sd3_lora" @@ -58,8 +61,6 @@ accelerate launch --num_cpu_threads_per_process 1 sd3_train_network.py --save_every_n_epochs=1 --mixed_precision="fp16" --gradient_checkpointing - --apply_lg_attn_mask - --apply_t5_attn_mask --weighting_scheme="sigma_sqrt" --blocks_to_swap=32 ``` @@ -73,10 +74,10 @@ accelerate launch --num_cpu_threads_per_process 1 sd3_train_network.py #### モデル関連 * `--pretrained_model_name_or_path=""` **[必須]** - * 学習のベースとなるSD3/3.5モデルの`.safetensors`ファイルのパスを指定します。単一ファイル形式(Diffusers/ComfyUI/AUTOMATIC1111形式)を想定しています。 + * 学習のベースとなるSD3/3.5モデルの`.safetensors`ファイルのパスを指定します。 * `--clip_l`, `--clip_g`, `--t5xxl`, `--vae`: - * ベースモデルが単一ファイル形式の場合、通常これらの指定は不要です(自動的にモデル内部から読み込まれます)。 - * もしText EncoderやVAEが別ファイルとして提供されている場合は、それぞれの`.safetensors`ファイルのパスを指定します。 + * ベースモデルが単一ファイル形式の場合、これらの指定は不要です(自動的にモデル内部から読み込まれます)。 + * Text Encoderが別ファイルとして提供されている場合は、それぞれの`.safetensors`ファイルのパスを指定します。`--vae` はベースモデルに含まれているため、通常は指定する必要はありません(明示的に異なるVAEを使用する場合のみ指定)。 #### SD3/3.5 学習パラメータ @@ -89,13 +90,13 @@ accelerate launch --num_cpu_threads_per_process 1 sd3_train_network.py * `--clip_l_dropout_rate`, `--clip_g_dropout_rate`, `--t5_dropout_rate`: * 各Text Encoderの出力に対して、指定した確率でドロップアウト(出力をゼロにする)を適用します。過学習の抑制に役立つ場合があります。デフォルトは`0.0`(ドロップアウトなし)です。 * `--pos_emb_random_crop_rate=` **[SD3.5向け]** - * MMDiTのPositional Embeddingに対してランダムクロップを適用する確率を指定します。SD3 5M (3.5) モデルで学習された機能であり、他のモデルでの効果は限定的です。デフォルトは`0.0`です。 -* `--enable_scaled_pos_embed` **[SD3.5向け]** - * マルチ解像度学習時に、解像度に応じてPositional Embeddingをスケーリングします。SD3 5M (3.5) モデルで学習された機能であり、他のモデルでの効果は限定的です。 + * MMDiTのPositional Embeddingに対してランダムクロップを適用する確率を指定します。[SD3.5M model card](https://huggingface.co/stabilityai/stable-diffusion-3.5-medium) で説明されています。デフォルトは`0.0`です。 +* `--enable_scaled_pos_embed` **[SD3.5向け]** **[実験的機能]** + * マルチ解像度学習時に、解像度に応じてPositional Embeddingをスケーリングします。デフォルトは`False`です。通常は指定不要です。 * `--training_shift=` - * 学習時のタイムステップ(ノイズレベル)の分布を調整するためのシフト値です。`weighting_scheme`に加えて適用されます。`1.0`より大きい値はノイズの大きい(構造寄り)領域を、小さい値はノイズの小さい(詳細寄り)領域を重視する傾向になります。デフォルトは`1.0`です。 + * 学習時のタイムステップ(ノイズレベル)の分布を調整するためのシフト値です。`weighting_scheme`に加えて適用されます。`1.0`より大きい値はノイズの大きい(構造寄り)領域を、小さい値はノイズの小さい(詳細寄り)領域を重視する傾向になります。デフォルトは`1.0`です。通常はデフォルト値で問題ありません。 * `--weighting_scheme=` - * 損失計算時のタイムステップ(ノイズレベル)に応じた重み付け方法を指定します。`sigma_sqrt`, `logit_normal`, `mode`, `cosmap`, `uniform` (または`none`) から選択します。SD3の論文では`sigma_sqrt`が使用されています。デフォルトは`uniform`です。 + * 損失計算時のタイムステップ(ノイズレベル)に応じた重み付け方法を指定します。`sigma_sqrt`, `logit_normal`, `mode`, `cosmap`, `uniform` (または`none`) から選択します。SD3の論文では`sigma_sqrt`が使用されています。デフォルトは`uniform`です。通常はデフォルト値で問題ありません。 * `--logit_mean`, `--logit_std`, `--mode_scale`: * `weighting_scheme`で`logit_normal`または`mode`を選択した場合に、その分布を制御するためのパラメータです。通常はデフォルト値で問題ありません。 diff --git a/docs/sdxl_train_network_advanced.md b/docs/sdxl_train_network_advanced.md new file mode 100644 index 00000000..ca718ad0 --- /dev/null +++ b/docs/sdxl_train_network_advanced.md @@ -0,0 +1,260 @@ +はい、承知いたしました。SDXL LoRA学習スクリプト `sdxl_train_network.py` の熟練した利用者向けの、機能全体の詳細を説明したドキュメントを作成します。 + +--- + +# 高度な設定: SDXL LoRA学習スクリプト `sdxl_train_network.py` 詳細ガイド + +このドキュメントでは、`sd-scripts` リポジトリに含まれる `sdxl_train_network.py` を使用した、SDXL (Stable Diffusion XL) モデルに対する LoRA (Low-Rank Adaptation) モデル学習の高度な設定オプションについて解説します。 + +基本的な使い方については、以下のドキュメントを参照してください。 + +* [LoRA学習スクリプト `train_network.py` の使い方](train_network.md) +* [SDXL LoRA学習スクリプト `sdxl_train_network.py` の使い方](sdxl_train_network.md) + +このガイドは、基本的なLoRA学習の経験があり、より詳細な設定や高度な機能を試したい熟練した利用者を対象としています。 + +**前提条件:** + +* `sd-scripts` リポジトリのクローンと Python 環境のセットアップが完了していること。 +* 学習用データセットの準備と設定(`.toml`ファイル)が完了していること。([データセット設定ガイド](link/to/dataset/config/doc)参照) +* 基本的なLoRA学習のコマンドライン実行経験があること。 + +## 1. コマンドライン引数 詳細解説 + +`sdxl_train_network.py` は `train_network.py` の機能を継承しつつ、SDXL特有の機能を追加しています。ここでは、SDXL LoRA学習に関連する主要なコマンドライン引数について、機能別に分類して詳細に解説します。 + +基本的な引数については、[LoRA学習スクリプト `train_network.py` の使い方](train_network.md#31-主要なコマンドライン引数) および [SDXL LoRA学習スクリプト `sdxl_train_network.py` の使い方](sdxl_train_network.md#31-主要なコマンドライン引数(差分)) を参照してください。 + +### 1.1. モデル読み込み関連 + +* `--pretrained_model_name_or_path="<モデルパス>"` **[必須]** + * 学習のベースとなる **SDXLモデル** を指定します。Hugging Face HubのモデルID、ローカルのDiffusers形式モデルディレクトリ、または`.safetensors`ファイルを指定できます。 + * 詳細は[基本ガイド](sdxl_train_network.md#モデル関連)を参照してください。 +* `--vae=""` + * オプションで、学習に使用するVAEを指定します。SDXLモデルに含まれるVAE以外を使用する場合に指定します。`.ckpt`または`.safetensors`ファイルを指定できます。 +* `--no_half_vae` + * 混合精度(`fp16`/`bf16`)使用時でもVAEを`float32`で動作させます。SDXLのVAEは`float16`で不安定になることがあるため、`fp16`指定時には有効にすることが推奨されます。`bf16`では通常不要です。 +* `--fp8_base` / `--fp8_base_unet` + * **実験的機能:** ベースモデル(U-Net, Text Encoder)またはU-NetのみをFP8で読み込み、VRAM使用量を削減します。PyTorch 2.1以上が必要です。詳細は[README](README.md#sd3-lora-training)の関連セクションを参照してください (SD3の説明ですがSDXLにも適用されます)。 + +### 1.2. データセット設定関連 + +* `--dataset_config="<設定ファイルのパス>"` **[必須]** + * データセットの設定を記述した`.toml`ファイルを指定します。SDXLでは高解像度データとバケツ機能(`.toml` で `enable_bucket = true` を指定)の利用が一般的です。 + * `.toml`ファイルの書き方の詳細は[データセット設定ガイド](link/to/dataset/config/doc)を参照してください。 + * アスペクト比バケツの解像度ステップ(`bucket_reso_steps`)は、SDXLでは8の倍数(例: 64)が一般的です。 + +### 1.3. 出力・保存関連 + +基本的なオプションは `train_network.py` と共通です。 + +* `--output_dir="<出力先ディレクトリ>"` **[必須]** +* `--output_name="<出力ファイル名>"` **[必須]** +* `--save_model_as="safetensors"` (推奨), `ckpt`, `pt`, `diffusers`, `diffusers_safetensors` +* `--save_precision="fp16"`, `"bf16"`, `"float"` + * モデルの保存精度を指定します。未指定時は学習時の精度(`fp16`, `bf16`等)で保存されます。 +* `--save_every_n_epochs=N` / `--save_every_n_steps=N` + * Nエポック/ステップごとにモデルを保存します。 +* `--save_last_n_epochs=M` / `--save_last_n_steps=M` + * エポック/ステップごとに保存する際、最新のM個のみを保持し、古いものは削除します。 +* `--save_state` / `--save_state_on_train_end` + * モデル保存時/学習終了時に、Optimizerの状態などを含む学習状態(`state`)を保存します。`--resume`オプションでの学習再開に必要です。 +* `--save_last_n_epochs_state=M` / `--save_last_n_steps_state=M` + * `state`の保存数をM個に制限します。`--save_last_n_epochs/steps`の指定を上書きします。 +* `--no_metadata` + * 出力モデルにメタデータを保存しません。 +* `--save_state_to_huggingface` / `--huggingface_repo_id` など + * Hugging Face Hubへのモデルやstateのアップロード関連オプション。詳細は[train\_util.py](train_util.py)や[huggingface\_util.py](huggingface_util.py)を参照してください。 + +### 1.4. ネットワークパラメータ (LoRA) + +基本的なオプションは `train_network.py` と共通です。 + +* `--network_module=networks.lora` **[必須]** +* `--network_dim=N` **[必須]** + * LoRAのランク (次元数) を指定します。SDXLでは32や64などが試されることが多いですが、データセットや目的に応じて調整が必要です。 +* `--network_alpha=M` + * LoRAのアルファ値。`network_dim`の半分程度、または`network_dim`と同じ値などが一般的です。デフォルトは1。 +* `--network_dropout=P` + * LoRAモジュール内のドロップアウト率 (0.0~1.0)。過学習抑制の効果が期待できます。デフォルトはNone (ドロップアウトなし)。 +* `--network_args ...` + * ネットワークモジュールへの追加引数を `key=value` 形式で指定します。LoRAでは以下の高度な設定が可能です。 + * **階層別 (Block-wise) 次元数/アルファ:** + * U-Netの各ブロックごとに異なる`dim`と`alpha`を指定できます。これにより、特定の層の影響を強めたり弱めたりする調整が可能です。 + * `block_dims`: U-NetのLinear層およびConv2d 1x1層に対するブロックごとのdimをカンマ区切りで指定します (SDXLでは23個の数値)。 + * `block_alphas`: 上記に対応するalpha値をカンマ区切りで指定します。 + * `conv_block_dims`: U-NetのConv2d 3x3層に対するブロックごとのdimをカンマ区切りで指定します。 + * `conv_block_alphas`: 上記に対応するalpha値をカンマ区切りで指定します。 + * 指定しないブロックは `--network_dim`/`--network_alpha` または `--conv_dim`/`--conv_alpha` (存在する場合) の値が使用されます。 + * 詳細は[LoRA の階層別学習率](train_network.md#lora-の階層別学習率) (train\_network.md内、SDXLでも同様に適用可能) や実装 ([lora.py](lora.py)) を参照してください。 + * **LoRA+:** + * `loraplus_lr_ratio=R`: LoRAの上向き重み(UP)の学習率を、下向き重み(DOWN)の学習率のR倍にします。学習速度の向上が期待できます。論文推奨は16。 + * `loraplus_unet_lr_ratio=RU`: U-Net部分のLoRA+学習率比を個別に指定します。 + * `loraplus_text_encoder_lr_ratio=RT`: Text Encoder部分のLoRA+学習率比を個別に指定します。(`--text_encoder_lr1`, `--text_encoder_lr2`で指定した学習率に乗算されます) + * 詳細は[README](../README.md#jan-17-2025--2025-01-17-version-090)や実装 ([lora.py](lora.py)) を参照してください。 +* `--network_train_unet_only` + * U-NetのLoRAモジュールのみを学習します。Text Encoderの学習を行わない場合に指定します。`--cache_text_encoder_outputs` を使用する場合は必須です。 +* `--network_train_text_encoder_only` + * Text EncoderのLoRAモジュールのみを学習します。U-Netの学習を行わない場合に指定します。 +* `--network_weights="<重みファイル>"` + * 学習済みのLoRA重みを読み込んで学習を開始します。ファインチューニングや学習再開に使用します。 +* `--dim_from_weights` + * `--network_weights` で指定した重みファイルからLoRAの次元数 (`dim`) を自動的に読み込みます。`--network_dim` の指定は不要になります。 + +### 1.5. 学習パラメータ + +* `--learning_rate=LR` + * 全体の学習率。各モジュール(`unet_lr`, `text_encoder_lr1`, `text_encoder_lr2`)のデフォルト値となります。`1e-4` や `4e-5` などが試されることが多いです。 +* `--unet_lr=LR_U` + * U-Net部分のLoRAモジュールの学習率。 +* `--text_encoder_lr1=LR_TE1` + * Text Encoder 1 (OpenCLIP ViT-G/14) のLoRAモジュールの学習率。通常、U-Netより小さい値 (例: `1e-5`, `2e-5`) が推奨されます。 +* `--text_encoder_lr2=LR_TE2` + * Text Encoder 2 (CLIP ViT-L/14) のLoRAモジュールの学習率。通常、U-Netより小さい値 (例: `1e-5`, `2e-5`) が推奨されます。 +* `--optimizer_type="..."` + * 使用するOptimizerを指定します。`AdamW8bit` (省メモリ、一般的), `Adafactor` (さらに省メモリ、SDXLフルモデル学習で実績あり), `Lion`, `DAdaptation`, `Prodigy`などが選択可能です。各Optimizerには追加の引数が必要な場合があります (`--optimizer_args`参照)。 + * `AdamW8bit` や `PagedAdamW8bit` (要 `bitsandbytes`) が一般的です。 + * `Adafactor` はメモリ効率が良いですが、設定がやや複雑です (相対ステップ(`relative_step=True`)推奨、学習率スケジューラは`adafactor`推奨)。 + * `DAdaptation`, `Prodigy` は学習率の自動調整機能がありますが、LoRA+との併用はできません。学習率は`1.0`程度を指定します。 + * 詳細は[train\_util.py](train_util.py)の`get_optimizer`関数を参照してください。 +* `--optimizer_args ...` + * Optimizerへの追加引数を `key=value` 形式で指定します (例: `"weight_decay=0.01"` `"betas=0.9,0.999"`). +* `--lr_scheduler="..."` + * 学習率スケジューラを指定します。`constant` (変化なし), `cosine` (コサインカーブ), `linear` (線形減衰), `constant_with_warmup` (ウォームアップ付き定数), `cosine_with_restarts` など。`cosine` や `constant_with_warmup` がよく使われます。 + * スケジューラによっては追加の引数が必要です (`--lr_scheduler_args`参照)。 + * `DAdaptation` や `Prodigy` などの自己学習率調整機能付きOptimizerを使用する場合、スケジューラは不要です (`constant` を指定)。 +* `--lr_warmup_steps=N` + * 学習率スケジューラのウォームアップステップ数。学習開始時に学習率を徐々に上げていく期間です。N < 1 の場合は全ステップ数に対する割合と解釈されます。 +* `--lr_scheduler_num_cycles=N` / `--lr_scheduler_power=P` + * 特定のスケジューラ (`cosine_with_restarts`, `polynomial`) のためのパラメータ。 +* `--max_train_steps=N` / `--max_train_epochs=N` + * 学習の総ステップ数またはエポック数を指定します。エポック指定が優先されます。 +* `--mixed_precision="bf16"` / `"fp16"` / `"no"` + * 混合精度学習の設定。SDXLでは `bf16` (対応GPUの場合) または `fp16` の使用が強く推奨されます。VRAM使用量を削減し、学習速度を向上させます。 +* `--full_fp16` / `--full_bf16` + * 勾配計算も含めて完全に半精度/bf16で行います。VRAM使用量をさらに削減できますが、学習の安定性に影響する可能性があります。 +* `--gradient_accumulation_steps=N` + * 勾配をNステップ分蓄積してからOptimizerを更新します。実質的なバッチサイズを `train_batch_size * N` に増やし、少ないVRAMで大きなバッチサイズ相当の効果を得られます。デフォルトは1。 +* `--max_grad_norm=N` + * 勾配クリッピングの閾値。勾配のノルムがNを超える場合にクリッピングします。デフォルトは1.0。`0`で無効。 +* `--gradient_checkpointing` + * メモリ使用量を大幅に削減しますが、学習速度は若干低下します。SDXLではメモリ消費が大きいため、有効にすることが推奨されます。 +* `--fused_backward_pass` + * **実験的機能:** 勾配計算とOptimizerのステップを融合し、VRAM使用量を削減します。SDXLで利用可能です。現在 `Adafactor` Optimizerのみ対応。Gradient Accumulationとは併用できません。 +* `--resume=""` + * `--save_state`で保存された学習状態から学習を再開します。Optimizerの状態や学習ステップ数などが復元されます。 + +### 1.6. キャッシュ機能関連 + +SDXLは計算コストが高いため、キャッシュ機能が効果的です。 + +* `--cache_latents` + * VAEの出力(Latent)をメモリにキャッシュします。VAEの計算を省略でき、VRAM使用量を削減し、学習を高速化します。**注意:** 画像に対するAugmentation (`color_aug`, `flip_aug`, `random_crop` 等) は無効になります。 +* `--cache_latents_to_disk` + * `--cache_latents` と併用し、キャッシュ先をディスクにします。大量のデータセットや複数回の学習で特に有効です。初回実行時にディスクにキャッシュが生成され、2回目以降はそれを読み込みます。 +* `--cache_text_encoder_outputs` + * Text Encoderの出力をメモリにキャッシュします。Text Encoderの計算を省略でき、VRAM使用量を削減し、学習を高速化します。**注意:** キャプションに対するAugmentation (`shuffle_caption`, `caption_dropout_rate` 等) は無効になります。**また、このオプションを使用する場合、Text EncoderのLoRAモジュールは学習できません (`--network_train_unet_only` の指定が必須です)。** +* `--cache_text_encoder_outputs_to_disk` + * `--cache_text_encoder_outputs` と併用し、キャッシュ先をディスクにします。 +* `--skip_cache_check` + * キャッシュファイルの内容の検証をスキップします。ファイルの存在確認は行われ、存在しない場合はキャッシュが生成されます。デバッグ等で意図的に再キャッシュしたい場合を除き、通常は指定不要です。 + +### 1.7. サンプル画像生成関連 + +基本的なオプションは `train_network.py` と共通です。 + +* `--sample_every_n_steps=N` / `--sample_every_n_epochs=N` + * Nステップ/エポックごとにサンプル画像を生成します。 +* `--sample_at_first` + * 学習開始前にサンプル画像を生成します。 +* `--sample_prompts="<プロンプトファイル>"` + * サンプル画像生成に使用するプロンプトを記述したファイル (`.txt`, `.toml`, `.json`) を指定します。書式は[gen\_img\_diffusers.py](gen_img_diffusers.py)に準じます。詳細は[ドキュメント](gen_img_README-ja.md)を参照してください。 +* `--sample_sampler="..."` + * サンプル画像生成時のサンプラー(スケジューラ)を指定します。`euler_a`, `dpm++_2m_karras` などが一般的です。選択肢は `--help` を参照してください。 + +### 1.8. Logging & Tracking 関連 + +* `--logging_dir="<ログディレクトリ>"` + * TensorBoardなどのログを出力するディレクトリを指定します。指定しない場合、ログは出力されません。 +* `--log_with="tensorboard"` / `"wandb"` / `"all"` + * 使用するログツールを指定します。`wandb`を使用する場合、`pip install wandb`が必要です。 +* `--log_prefix="<プレフィックス>"` + * `logging_dir` 内に作成されるサブディレクトリ名の接頭辞を指定します。 +* `--wandb_api_key=""` / `--wandb_run_name="<実行名>"` + * Weights & Biases (wandb) 使用時のオプション。 +* `--log_tracker_name` / `--log_tracker_config` + * 高度なトラッカー設定用オプション。通常は指定不要。 +* `--log_config` + * 学習開始時に、使用された学習設定(一部の機密情報を除く)をログに出力します。再現性の確保に役立ちます。 + +### 1.9. 正則化・高度な学習テクニック関連 + +* `--noise_offset=N` + * ノイズオフセットを有効にし、その値を指定します。画像の明るさやコントラストの偏りを改善する効果が期待できます。SDXLのベースモデルはこの値で学習されているため、有効にすることが推奨されます (例: 0.0357)。 +* `--noise_offset_random_strength` + * ノイズオフセットの強度を0から指定値の間でランダムに変動させます。 +* `--adaptive_noise_scale=N` + * Latentの平均絶対値に応じてノイズオフセットを調整します。`--noise_offset`と併用します。 +* `--multires_noise_iterations=N` / `--multires_noise_discount=D` + * 複数解像度ノイズを有効にします。異なる周波数成分のノイズを加えることで、ディテールの再現性を向上させる効果が期待できます。イテレーション回数N (6-10程度) と割引率D (0.3程度) を指定します。 +* `--ip_noise_gamma=G` / `--ip_noise_gamma_random_strength` + * Input Perturbation Noiseを有効にします。入力(Latent)に微小なノイズを加えて正則化を行います。Gamma値 (0.1程度) を指定します。`random_strength`で強度をランダム化できます。 +* `--min_snr_gamma=N` + * Min-SNR Weighting Strategy を適用します。学習初期のノイズが大きいタイムステップでのLossの重みを調整し、学習を安定させます。`N=5` などが使用されます。 +* `--scale_v_pred_loss_like_noise_pred` + * v-predictionモデルにおいて、vの予測ロスをノイズ予測ロスと同様のスケールに調整します。SDXLはv-predictionではないため、**通常は使用しません**。 +* `--v_pred_like_loss=N` + * ノイズ予測モデルにv予測ライクなロスを追加します。`N`でその重みを指定します。SDXLでは**通常は使用しません**。 +* `--debiased_estimation_loss` + * Debiased EstimationによるLoss計算を行います。Min-SNRと類似の目的を持ちますが、異なるアプローチです。 +* `--loss_type="l1"` / `"l2"` / `"huber"` / `"smooth_l1"` + * 損失関数を指定します。デフォルトは`l2` (MSE)。`huber`や`smooth_l1`は外れ値に頑健な損失関数です。 +* `--huber_schedule="constant"` / `"exponential"` / `"snr"` + * `huber`または`smooth_l1`損失使用時のスケジューリング方法。`snr`が推奨されています。 +* `--huber_c=C` / `--huber_scale=S` + * `huber`または`smooth_l1`損失のパラメータ。 +* `--masked_loss` + * マスク画像に基づいてLoss計算領域を限定します。データセット設定で`conditioning_data_dir`にマスク画像(白黒)を指定する必要があります。詳細は[マスクロスについて](masked_loss_README.md)を参照してください。 + +### 1.10. 分散学習・その他 + +* `--seed=N` + * 乱数シードを指定します。学習の再現性を確保したい場合に設定します。 +* `--max_token_length=N` (`75`, `150`, `225`) + * Text Encoderが処理するトークンの最大長。SDXLでは通常`75` (デフォルト) または `150`, `225`。長くするとより複雑なプロンプトを扱えますが、VRAM使用量が増加します。 +* `--clip_skip=N` + * Text Encoderの最終層からN層スキップした層の出力を使用します。SDXLでは**通常使用しません**。 +* `--lowram` / `--highvram` + * メモリ使用量の最適化に関するオプション。`--lowram`はColabなどRAM < VRAM環境向け、`--highvram`はVRAM潤沢な環境向け。 +* `--persistent_data_loader_workers` / `--max_data_loader_n_workers=N` + * DataLoaderのワーカプロセスに関する設定。エポック間の待ち時間やメモリ使用量に影響します。 +* `--config_file="<設定ファイル>"` / `--output_config` + * コマンドライン引数の代わりに`.toml`ファイルを使用/出力するオプション。 +* **Accelerate/DeepSpeed関連:** (`--ddp_timeout`, `--ddp_gradient_as_bucket_view`, `--ddp_static_graph`) + * 分散学習時の詳細設定。通常はAccelerateの設定 (`accelerate config`) で十分です。DeepSpeedを使用する場合は、別途設定が必要です。 + +## 2. その他のTips + +* **VRAM使用量:** SDXL LoRA学習は多くのVRAMを必要とします。24GB VRAMでも設定によってはメモリ不足になることがあります。以下の設定でVRAM使用量を削減できます。 + * `--mixed_precision="bf16"` または `"fp16"` (必須級) + * `--gradient_checkpointing` (強く推奨) + * `--cache_latents` / `--cache_text_encoder_outputs` (効果大、制約あり) + * `--optimizer_type="AdamW8bit"` または `"Adafactor"` + * `--gradient_accumulation_steps` の値を増やす (バッチサイズを小さくする) + * `--full_fp16` / `--full_bf16` (安定性に注意) + * `--fp8_base` / `--fp8_base_unet` (実験的) + * `--fused_backward_pass` (Adafactor限定、実験的) +* **学習率:** SDXL LoRAの適切な学習率はデータセットや`network_dim`/`alpha`に依存します。`1e-4` ~ `4e-5` (U-Net), `1e-5` ~ `2e-5` (Text Encoders) あたりから試すのが一般的です。 +* **学習時間:** 高解像度データとSDXLモデルのサイズのため、学習には時間がかかります。キャッシュ機能や適切なハードウェアの利用が重要です。 +* **トラブルシューティング:** + * **NaN Loss:** 学習率が高すぎる、混合精度の設定が不適切 (`fp16`時の`--no_half_vae`未指定など)、データセットの問題などが考えられます。 + * **VRAM不足 (OOM):** 上記のVRAM削減策を試してください。 + * **学習が進まない:** 学習率が低すぎる、Optimizer/Schedulerの設定が不適切、データセットの問題などが考えられます。 + +## 3. おわりに + +`sdxl_train_network.py` は非常に多くのオプションを提供しており、SDXL LoRA学習の様々な側面をカスタマイズできます。このドキュメントが、より高度な設定やチューニングを行う際の助けとなれば幸いです。 + +不明な点や詳細については、各スクリプトの `--help` オプションや、リポジトリ内の他のドキュメント、実装コード自体を参照してください。 + +--- \ No newline at end of file From 176baa6b95ae1f9eb6fcc02665f4f1966ae47df9 Mon Sep 17 00:00:00 2001 From: Kohya S Date: Wed, 16 Apr 2025 12:32:43 +0900 Subject: [PATCH 4/9] doc: update sd3 and sdxl training guides --- docs/sd3_train_network.md | 2 ++ docs/sdxl_train_network_advanced.md | 22 +++++++++++----------- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/docs/sd3_train_network.md b/docs/sd3_train_network.md index 95f7ce62..2911fdf2 100644 --- a/docs/sd3_train_network.md +++ b/docs/sd3_train_network.md @@ -1,3 +1,5 @@ +ステータス:内容を一通り確認した + # `sd3_train_network.py` を用いたStable Diffusion 3/3.5モデルのLoRA学習ガイド このドキュメントでは、`sd-scripts`リポジトリに含まれる`sd3_train_network.py`を使用して、Stable Diffusion 3 (SD3) および Stable Diffusion 3.5 (SD3.5) モデルに対するLoRA (Low-Rank Adaptation) モデルを学習する基本的な手順について解説します。 diff --git a/docs/sdxl_train_network_advanced.md b/docs/sdxl_train_network_advanced.md index ca718ad0..a736f0b3 100644 --- a/docs/sdxl_train_network_advanced.md +++ b/docs/sdxl_train_network_advanced.md @@ -1,4 +1,4 @@ -はい、承知いたしました。SDXL LoRA学習スクリプト `sdxl_train_network.py` の熟練した利用者向けの、機能全体の詳細を説明したドキュメントを作成します。 +ステータス:確認中 --- @@ -35,14 +35,14 @@ * `--no_half_vae` * 混合精度(`fp16`/`bf16`)使用時でもVAEを`float32`で動作させます。SDXLのVAEは`float16`で不安定になることがあるため、`fp16`指定時には有効にすることが推奨されます。`bf16`では通常不要です。 * `--fp8_base` / `--fp8_base_unet` - * **実験的機能:** ベースモデル(U-Net, Text Encoder)またはU-NetのみをFP8で読み込み、VRAM使用量を削減します。PyTorch 2.1以上が必要です。詳細は[README](README.md#sd3-lora-training)の関連セクションを参照してください (SD3の説明ですがSDXLにも適用されます)。 + * **実験的機能:** ベースモデル(U-Net, Text Encoder)またはU-NetのみをFP8で読み込み、VRAM使用量を削減します。PyTorch 2.1以上が必要です。詳細は TODO 後でドキュメントを追加 の関連セクションを参照してください (SD3の説明ですがSDXLにも適用されます)。 ### 1.2. データセット設定関連 -* `--dataset_config="<設定ファイルのパス>"` **[必須]** +* `--dataset_config="<設定ファイルのパス>"` * データセットの設定を記述した`.toml`ファイルを指定します。SDXLでは高解像度データとバケツ機能(`.toml` で `enable_bucket = true` を指定)の利用が一般的です。 * `.toml`ファイルの書き方の詳細は[データセット設定ガイド](link/to/dataset/config/doc)を参照してください。 - * アスペクト比バケツの解像度ステップ(`bucket_reso_steps`)は、SDXLでは8の倍数(例: 64)が一般的です。 + * アスペクト比バケツの解像度ステップ(`bucket_reso_steps`)は、SDXLでは32の倍数とする必要があります。 ### 1.3. 出力・保存関連 @@ -64,7 +64,7 @@ * `--no_metadata` * 出力モデルにメタデータを保存しません。 * `--save_state_to_huggingface` / `--huggingface_repo_id` など - * Hugging Face Hubへのモデルやstateのアップロード関連オプション。詳細は[train\_util.py](train_util.py)や[huggingface\_util.py](huggingface_util.py)を参照してください。 + * Hugging Face Hubへのモデルやstateのアップロード関連オプション。詳細は TODO ドキュメントを追加 を参照してください。 ### 1.4. ネットワークパラメータ (LoRA) @@ -97,14 +97,14 @@ * `--network_train_text_encoder_only` * Text EncoderのLoRAモジュールのみを学習します。U-Netの学習を行わない場合に指定します。 * `--network_weights="<重みファイル>"` - * 学習済みのLoRA重みを読み込んで学習を開始します。ファインチューニングや学習再開に使用します。 + * 学習済みのLoRA重みを読み込んで学習を開始します。ファインチューニングや学習再開に使用します。`--resume` との違いは、このオプションはLoRAモジュールの重みのみを読み込み、`--resume` はOptimizerの状態や学習ステップ数なども復元します。 * `--dim_from_weights` * `--network_weights` で指定した重みファイルからLoRAの次元数 (`dim`) を自動的に読み込みます。`--network_dim` の指定は不要になります。 ### 1.5. 学習パラメータ * `--learning_rate=LR` - * 全体の学習率。各モジュール(`unet_lr`, `text_encoder_lr1`, `text_encoder_lr2`)のデフォルト値となります。`1e-4` や `4e-5` などが試されることが多いです。 + * 全体の学習率。各モジュール(`unet_lr`, `text_encoder_lr1`, `text_encoder_lr2`)のデフォルト値となります。`1e-3` や `1e-4` などが試されることが多いです。 * `--unet_lr=LR_U` * U-Net部分のLoRAモジュールの学習率。 * `--text_encoder_lr1=LR_TE1` @@ -120,7 +120,7 @@ * `--optimizer_args ...` * Optimizerへの追加引数を `key=value` 形式で指定します (例: `"weight_decay=0.01"` `"betas=0.9,0.999"`). * `--lr_scheduler="..."` - * 学習率スケジューラを指定します。`constant` (変化なし), `cosine` (コサインカーブ), `linear` (線形減衰), `constant_with_warmup` (ウォームアップ付き定数), `cosine_with_restarts` など。`cosine` や `constant_with_warmup` がよく使われます。 + * 学習率スケジューラを指定します。`constant` (変化なし), `cosine` (コサインカーブ), `linear` (線形減衰), `constant_with_warmup` (ウォームアップ付き定数), `cosine_with_restarts` など。`constant` や `cosine` 、 `constant_with_warmup` がよく使われます。 * スケジューラによっては追加の引数が必要です (`--lr_scheduler_args`参照)。 * `DAdaptation` や `Prodigy` などの自己学習率調整機能付きOptimizerを使用する場合、スケジューラは不要です (`constant` を指定)。 * `--lr_warmup_steps=N` @@ -132,7 +132,7 @@ * `--mixed_precision="bf16"` / `"fp16"` / `"no"` * 混合精度学習の設定。SDXLでは `bf16` (対応GPUの場合) または `fp16` の使用が強く推奨されます。VRAM使用量を削減し、学習速度を向上させます。 * `--full_fp16` / `--full_bf16` - * 勾配計算も含めて完全に半精度/bf16で行います。VRAM使用量をさらに削減できますが、学習の安定性に影響する可能性があります。 + * 勾配計算も含めて完全に半精度/bf16で行います。VRAM使用量をさらに削減できますが、学習の安定性に影響する可能性があります。VRAMがどうしても足りない場合に使用します。 * `--gradient_accumulation_steps=N` * 勾配をNステップ分蓄積してからOptimizerを更新します。実質的なバッチサイズを `train_batch_size * N` に増やし、少ないVRAMで大きなバッチサイズ相当の効果を得られます。デフォルトは1。 * `--max_grad_norm=N` @@ -190,13 +190,13 @@ SDXLは計算コストが高いため、キャッシュ機能が効果的です ### 1.9. 正則化・高度な学習テクニック関連 * `--noise_offset=N` - * ノイズオフセットを有効にし、その値を指定します。画像の明るさやコントラストの偏りを改善する効果が期待できます。SDXLのベースモデルはこの値で学習されているため、有効にすることが推奨されます (例: 0.0357)。 + * ノイズオフセットを有効にし、その値を指定します。画像の明るさやコントラストの偏りを改善する効果が期待できます。SDXLのベースモデルはこの値で学習されているため、有効にすることが推奨されます (例: 0.0357)。元々の技術解説は[こちら](https://www.crosslabs.org/blog/diffusion-with-offset-noise)。 * `--noise_offset_random_strength` * ノイズオフセットの強度を0から指定値の間でランダムに変動させます。 * `--adaptive_noise_scale=N` * Latentの平均絶対値に応じてノイズオフセットを調整します。`--noise_offset`と併用します。 * `--multires_noise_iterations=N` / `--multires_noise_discount=D` - * 複数解像度ノイズを有効にします。異なる周波数成分のノイズを加えることで、ディテールの再現性を向上させる効果が期待できます。イテレーション回数N (6-10程度) と割引率D (0.3程度) を指定します。 + * 複数解像度ノイズを有効にします。異なる周波数成分のノイズを加えることで、ディテールの再現性を向上させる効果が期待できます。イテレーション回数N (6-10程度) と割引率D (0.3程度) を指定します。技術解説は[こちら](https://wandb.ai/johnowhitaker/multires_noise/reports/Multi-Resolution-Noise-for-Diffusion-Model-Training--VmlldzozNjYyOTU2)。 * `--ip_noise_gamma=G` / `--ip_noise_gamma_random_strength` * Input Perturbation Noiseを有効にします。入力(Latent)に微小なノイズを加えて正則化を行います。Gamma値 (0.1程度) を指定します。`random_strength`で強度をランダム化できます。 * `--min_snr_gamma=N` From 19a180ff909e5f6deb46d2cac5b22615df6ad9b1 Mon Sep 17 00:00:00 2001 From: "Kohya S." <52813779+kohya-ss@users.noreply.github.com> Date: Sat, 17 May 2025 14:28:26 +0900 Subject: [PATCH 5/9] Add English versions with Japanese in details --- docs/flux_train_network.md | 84 ++++++++++- docs/sd3_train_network.md | 213 ++++++++++++++++++++-------- docs/sdxl_train_network_advanced.md | 89 +++++++++++- 3 files changed, 325 insertions(+), 61 deletions(-) diff --git a/docs/flux_train_network.md b/docs/flux_train_network.md index 46eee3e7..4d7c2d46 100644 --- a/docs/flux_train_network.md +++ b/docs/flux_train_network.md @@ -1,3 +1,85 @@ +Status: reviewed + +# LoRA Training Guide for FLUX.1 using `flux_train_network.py` / `flux_train_network.py` を用いたFLUX.1モデルのLoRA学習ガイド + +This document explains how to train LoRA models for the FLUX.1 model using `flux_train_network.py` included in the `sd-scripts` repository. + +## 1. Introduction / はじめに + +`flux_train_network.py` trains additional networks such as LoRA on the FLUX.1 model, which uses a transformer-based architecture different from Stable Diffusion. Two text encoders, CLIP-L and T5-XXL, and a dedicated AutoEncoder are used. + +This guide assumes you know the basics of LoRA training. For common options see [train_network.py](train_network.md) and [sdxl_train_network.py](sdxl_train_network.md). + +**Prerequisites:** + +* The repository is cloned and the Python environment is ready. +* A training dataset is prepared. See the dataset configuration guide. + +## 2. Differences from `train_network.py` / `train_network.py` との違い + +`flux_train_network.py` is based on `train_network.py` but adapted for FLUX.1. Main differences include required arguments for the FLUX.1 model, CLIP-L, T5-XXL and AE, different model structure, and some incompatible options from Stable Diffusion. + +## 3. Preparation / 準備 + +Before starting training you need: + +1. **Training script:** `flux_train_network.py` +2. **FLUX.1 model file** and text encoder files (`clip_l`, `t5xxl`) and AE file. +3. **Dataset definition file (.toml)** such as `my_flux_dataset_config.toml`. + +## 4. Running the Training / 学習の実行 + +Run `flux_train_network.py` from the terminal with FLUX.1 specific arguments. Example: + +```bash +accelerate launch --num_cpu_threads_per_process 1 flux_train_network.py \ + --pretrained_model_name_or_path="" \ + --clip_l="" \ + --t5xxl="" \ + --ae="" \ + --dataset_config="my_flux_dataset_config.toml" \ + --output_dir="" \ + --output_name="my_flux_lora" \ + --save_model_as=safetensors \ + --network_module=networks.lora_flux \ + --network_dim=16 \ + --network_alpha=1 \ + --learning_rate=1e-4 \ + --optimizer_type="AdamW8bit" \ + --lr_scheduler="constant" \ + --sdpa \ + --max_train_epochs=10 \ + --save_every_n_epochs=1 \ + --mixed_precision="fp16" \ + --gradient_checkpointing \ + --guidance_scale=1.0 \ + --timestep_sampling="flux_shift" \ + --blocks_to_swap=18 \ + --cache_text_encoder_outputs \ + --cache_latents +``` + +### 4.1. Explanation of Key Options / 主要なコマンドライン引数の解説 + +The script adds FLUX.1 specific arguments such as guidance scale, timestep sampling, block swapping, and options for training CLIP-L and T5-XXL LoRA modules. Some Stable Diffusion options like `--v2` and `--clip_skip` are not used. + +### 4.2. Starting Training / 学習の開始 + +Training begins once you run the command with the required options. Log checking is the same as in `train_network.py`. + +## 5. Using the Trained Model / 学習済みモデルの利用 + +After training, a LoRA model file is saved in `output_dir` and can be used in inference environments supporting FLUX.1 (e.g. ComfyUI + Flux nodes). + +## 6. Others / その他 + +Additional notes on VRAM optimization, training options, multi-resolution datasets, block selection and text encoder LoRA are provided in the Japanese section. + +
+日本語 + + + # `flux_train_network.py` を用いたFLUX.1モデルのLoRA学習ガイド このドキュメントでは、`sd-scripts`リポジトリに含まれる`flux_train_network.py`を使用して、FLUX.1モデルに対するLoRA (Low-Rank Adaptation) モデルを学習する基本的な手順について解説します。 @@ -312,4 +394,4 @@ resolution = [512, 512] num_repeats = 1 ``` -各解像度セクションの`[[datasets.subsets]]`部分は、データセットディレクトリを定義します。各解像度に対して同じディレクトリを指定してください。 \ No newline at end of file +各解像度セクションの`[[datasets.subsets]]`部分は、データセットディレクトリを定義します。各解像度に対して同じディレクトリを指定してください。
diff --git a/docs/sd3_train_network.md b/docs/sd3_train_network.md index 2911fdf2..e10829aa 100644 --- a/docs/sd3_train_network.md +++ b/docs/sd3_train_network.md @@ -1,11 +1,25 @@ +Status: reviewed + +# LoRA Training Guide for Stable Diffusion 3/3.5 using `sd3_train_network.py` / `sd3_train_network.py` を用いたStable Diffusion 3/3.5モデルのLoRA学習ガイド + +This document explains how to train LoRA (Low-Rank Adaptation) models for Stable Diffusion 3 (SD3) and Stable Diffusion 3.5 (SD3.5) using `sd3_train_network.py` in the `sd-scripts` repository. + +## 1. Introduction / はじめに + +`sd3_train_network.py` trains additional networks such as LoRA for SD3/3.5 models. SD3 adopts a new architecture called MMDiT (Multi-Modal Diffusion Transformer), so its structure differs from previous Stable Diffusion models. With this script you can create LoRA models specialized for SD3/3.5. + +This guide assumes you already understand the basics of LoRA training. For common usage and options, see the [train_network.py guide](train_network.md). Some parameters are the same as those in [`sdxl_train_network.py`](sdxl_train_network.md). + +**Prerequisites:** + +* The `sd-scripts` repository has been cloned and the Python environment is ready. +* A training dataset has been prepared. See the [Dataset Configuration Guide](link/to/dataset/config/doc). +* SD3/3.5 model files for training are available. + +
+日本語 ステータス:内容を一通り確認した -# `sd3_train_network.py` を用いたStable Diffusion 3/3.5モデルのLoRA学習ガイド - -このドキュメントでは、`sd-scripts`リポジトリに含まれる`sd3_train_network.py`を使用して、Stable Diffusion 3 (SD3) および Stable Diffusion 3.5 (SD3.5) モデルに対するLoRA (Low-Rank Adaptation) モデルを学習する基本的な手順について解説します。 - -## 1. はじめに - `sd3_train_network.py`は、Stable Diffusion 3/3.5モデルに対してLoRAなどの追加ネットワークを学習させるためのスクリプトです。SD3は、MMDiT (Multi-Modal Diffusion Transformer) と呼ばれる新しいアーキテクチャを採用しており、従来のStable Diffusionモデルとは構造が異なります。このスクリプトを使用することで、SD3/3.5モデルに特化したLoRAモデルを作成できます。 このガイドは、基本的なLoRA学習の手順を理解しているユーザーを対象としています。基本的な使い方や共通のオプションについては、[`train_network.py`のガイド](train_network.md)を参照してください。また一部のパラメータは [`sdxl_train_network.py`](sdxl_train_network.md) と同様のものがあるため、そちらも参考にしてください。 @@ -15,9 +29,20 @@ * `sd-scripts`リポジトリのクローンとPython環境のセットアップが完了していること。 * 学習用データセットの準備が完了していること。(データセットの準備については[データセット設定ガイド](link/to/dataset/config/doc)を参照してください) * 学習対象のSD3/3.5モデルファイルが準備できていること。 +
-## 2. `train_network.py` との違い +## 2. Differences from `train_network.py` / `train_network.py` との違い +`sd3_train_network.py` is based on `train_network.py` but modified for SD3/3.5. Main differences are: + +* **Target models:** Stable Diffusion 3 and 3.5 Medium/Large. +* **Model structure:** Uses MMDiT (Transformer based) instead of U-Net and employs three text encoders: CLIP-L, CLIP-G and T5-XXL. The VAE is not compatible with SDXL. +* **Arguments:** Options exist to specify the SD3/3.5 model, text encoders and VAE. With a single `.safetensors` file, these paths are detected automatically, so separate paths are optional. +* **Incompatible arguments:** Stable Diffusion v1/v2 options such as `--v2`, `--v_parameterization` and `--clip_skip` are not used. +* **SD3 specific options:** Additional parameters for attention masks, dropout rates, positional embedding adjustments (for SD3.5), timestep sampling and loss weighting. + +
+日本語 `sd3_train_network.py`は`train_network.py`をベースに、SD3/3.5モデルに対応するための変更が加えられています。主な違いは以下の通りです。 * **対象モデル:** Stable Diffusion 3, 3.5 Medium / Large モデルを対象とします。 @@ -25,9 +50,18 @@ * **引数:** SD3/3.5モデル、Text Encoder群、VAEを指定する引数があります。ただし、単一ファイルの`.safetensors`形式であれば、内部で自動的に分離されるため、個別のパス指定は必須ではありません。 * **一部引数の非互換性:** Stable Diffusion v1/v2向けの引数(例: `--v2`, `--v_parameterization`, `--clip_skip`)はSD3/3.5の学習では使用されません。 * **SD3特有の引数:** Text Encoderのアテンションマスクやドロップアウト率、Positional Embeddingの調整(SD3.5向け)、タイムステップのサンプリングや損失の重み付けに関する引数が追加されています。 +
-## 3. 準備 +## 3. Preparation / 準備 +The following files are required before starting training: + +1. **Training script:** `sd3_train_network.py` +2. **SD3/3.5 model file:** `.safetensors` file for the base model and paths to each text encoder. Single-file format can also be used. +3. **Dataset definition file (.toml):** Dataset settings in TOML format. (See the [Dataset Configuration Guide](link/to/dataset/config/doc).) In this document we use `my_sd3_dataset_config.toml` as an example. + +
+日本語 学習を開始する前に、以下のファイルが必要です。 1. **学習スクリプト:** `sd3_train_network.py` @@ -35,43 +69,107 @@ * 単一ファイル形式も使用可能です。 3. **データセット定義ファイル (.toml):** 学習データセットの設定を記述したTOML形式のファイル。(詳細は[データセット設定ガイド](link/to/dataset/config/doc)を参照してください)。 * 例として`my_sd3_dataset_config.toml`を使用します。 +
-## 4. 学習の実行 +## 4. Running the Training / 学習の実行 +Execute `sd3_train_network.py` from the terminal to start training. The overall command-line format is the same as `train_network.py`, but SD3/3.5 specific options must be supplied. + +Example command: + +```bash +accelerate launch --num_cpu_threads_per_process 1 sd3_train_network.py \ + --pretrained_model_name_or_path="" \ + --clip_l="" \ + --clip_g="" \ + --t5xxl="" \ + --dataset_config="my_sd3_dataset_config.toml" \ + --output_dir="" \ + --output_name="my_sd3_lora" \ + --save_model_as=safetensors \ + --network_module=networks.lora \ + --network_dim=16 \ + --network_alpha=1 \ + --learning_rate=1e-4 \ + --optimizer_type="AdamW8bit" \ + --lr_scheduler="constant" \ + --sdpa \ + --max_train_epochs=10 \ + --save_every_n_epochs=1 \ + --mixed_precision="fp16" \ + --gradient_checkpointing \ + --weighting_scheme="sigma_sqrt" \ + --blocks_to_swap=32 +``` + +*(Write the command on one line or use `\` or `^` for line breaks.)* + +
+日本語 学習は、ターミナルから`sd3_train_network.py`を実行することで開始します。基本的なコマンドラインの構造は`train_network.py`と同様ですが、SD3/3.5特有の引数を指定する必要があります。 以下に、基本的なコマンドライン実行例を示します。 ```bash -accelerate launch --num_cpu_threads_per_process 1 sd3_train_network.py - --pretrained_model_name_or_path="" +accelerate launch --num_cpu_threads_per_process 1 sd3_train_network.py + --pretrained_model_name_or_path="" --clip_l="" - --clip_g="" - --t5xxl="" - --dataset_config="my_sd3_dataset_config.toml" - --output_dir="" - --output_name="my_sd3_lora" - --save_model_as=safetensors - --network_module=networks.lora - --network_dim=16 - --network_alpha=1 - --learning_rate=1e-4 - --optimizer_type="AdamW8bit" - --lr_scheduler="constant" - --sdpa - --max_train_epochs=10 - --save_every_n_epochs=1 - --mixed_precision="fp16" - --gradient_checkpointing - --weighting_scheme="sigma_sqrt" + --clip_g="" + --t5xxl="" + --dataset_config="my_sd3_dataset_config.toml" + --output_dir="" + --output_name="my_sd3_lora" + --save_model_as=safetensors + --network_module=networks.lora + --network_dim=16 + --network_alpha=1 + --learning_rate=1e-4 + --optimizer_type="AdamW8bit" + --lr_scheduler="constant" + --sdpa + --max_train_epochs=10 + --save_every_n_epochs=1 + --mixed_precision="fp16" + --gradient_checkpointing + --weighting_scheme="sigma_sqrt" --blocks_to_swap=32 ``` ※実際には1行で書くか、適切な改行文字(`\` または `^`)を使用してください。 +
-### 4.1. 主要なコマンドライン引数の解説(`train_network.py`からの追加・変更点) +### 4.1. Explanation of Key Options / 主要なコマンドライン引数の解説 -[`train_network.py`のガイド](train_network.md)で説明されている引数に加え、以下のSD3/3.5特有の引数を指定します。共通の引数(`--output_dir`, `--output_name`, `--network_module`, `--network_dim`, `--network_alpha`, `--learning_rate`など)については、上記ガイドを参照してください。 +Besides the arguments explained in the [train_network.py guide](train_network.md), specify the following SD3/3.5 options. For shared options (`--output_dir`, `--output_name`, etc.), see that guide. + +#### Model Options / モデル関連 + +* `--pretrained_model_name_or_path=""` **required** – Path to the SD3/3.5 model. +* `--clip_l`, `--clip_g`, `--t5xxl`, `--vae` – Skip these if the base model is a single file; otherwise specify each `.safetensors` path. `--vae` is usually unnecessary unless you use a different VAE. + +#### SD3/3.5 Training Parameters / SD3/3.5 学習パラメータ + +* `--t5xxl_max_token_length=` – Max token length for T5-XXL. Default `256`. +* `--apply_lg_attn_mask` – Apply an attention mask to CLIP-L/CLIP-G outputs. +* `--apply_t5_attn_mask` – Apply an attention mask to T5-XXL outputs. +* `--clip_l_dropout_rate`, `--clip_g_dropout_rate`, `--t5_dropout_rate` – Dropout rates for the text encoders. Default `0.0`. +* `--pos_emb_random_crop_rate=` **[SD3.5]** – Probability of randomly cropping the positional embedding. +* `--enable_scaled_pos_embed` **[SD3.5][experimental]** – Scale positional embeddings when training with multiple resolutions. +* `--training_shift=` – Shift applied to the timestep distribution. Default `1.0`. +* `--weighting_scheme=` – Weighting method for loss by timestep. Default `uniform`. +* `--logit_mean`, `--logit_std`, `--mode_scale` – Parameters for `logit_normal` or `mode` weighting. + +#### Memory and Speed / メモリ・速度関連 + +* `--blocks_to_swap=` **[experimental]** – Swap a number of Transformer blocks between CPU and GPU. More blocks reduce VRAM but slow training. Cannot be used with `--cpu_offload_checkpointing`. + +#### Incompatible or Deprecated Options / 非互換・非推奨の引数 + +* `--v2`, `--v_parameterization`, `--clip_skip` – Options for Stable Diffusion v1/v2 that are not used for SD3/3.5. + +
+日本語 +[`train_network.py`のガイド](train_network.md)で説明されている引数に加え、以下のSD3/3.5特有の引数を指定します。共通の引数については、上記ガイドを参照してください。 #### モデル関連 @@ -83,43 +181,42 @@ accelerate launch --num_cpu_threads_per_process 1 sd3_train_network.py #### SD3/3.5 学習パラメータ -* `--t5xxl_max_token_length=` - * T5-XXL Text Encoderで使用するトークンの最大長を指定します。SD3のデフォルトは`256`です。データセットのキャプション長に合わせて調整が必要な場合があります。 -* `--apply_lg_attn_mask` - * CLIP-LおよびCLIP-Gの出力に対して、パディングトークンに対応するアテンションマスク(ゼロ埋め)を適用します。 -* `--apply_t5_attn_mask` - * T5-XXLの出力に対して、パディングトークンに対応するアテンションマスク(ゼロ埋め)を適用します。 -* `--clip_l_dropout_rate`, `--clip_g_dropout_rate`, `--t5_dropout_rate`: - * 各Text Encoderの出力に対して、指定した確率でドロップアウト(出力をゼロにする)を適用します。過学習の抑制に役立つ場合があります。デフォルトは`0.0`(ドロップアウトなし)です。 -* `--pos_emb_random_crop_rate=` **[SD3.5向け]** - * MMDiTのPositional Embeddingに対してランダムクロップを適用する確率を指定します。[SD3.5M model card](https://huggingface.co/stabilityai/stable-diffusion-3.5-medium) で説明されています。デフォルトは`0.0`です。 -* `--enable_scaled_pos_embed` **[SD3.5向け]** **[実験的機能]** - * マルチ解像度学習時に、解像度に応じてPositional Embeddingをスケーリングします。デフォルトは`False`です。通常は指定不要です。 -* `--training_shift=` - * 学習時のタイムステップ(ノイズレベル)の分布を調整するためのシフト値です。`weighting_scheme`に加えて適用されます。`1.0`より大きい値はノイズの大きい(構造寄り)領域を、小さい値はノイズの小さい(詳細寄り)領域を重視する傾向になります。デフォルトは`1.0`です。通常はデフォルト値で問題ありません。 -* `--weighting_scheme=` - * 損失計算時のタイムステップ(ノイズレベル)に応じた重み付け方法を指定します。`sigma_sqrt`, `logit_normal`, `mode`, `cosmap`, `uniform` (または`none`) から選択します。SD3の論文では`sigma_sqrt`が使用されています。デフォルトは`uniform`です。通常はデフォルト値で問題ありません。 -* `--logit_mean`, `--logit_std`, `--mode_scale`: - * `weighting_scheme`で`logit_normal`または`mode`を選択した場合に、その分布を制御するためのパラメータです。通常はデフォルト値で問題ありません。 +* `--t5xxl_max_token_length=` – T5-XXLで使用するトークンの最大長を指定します。デフォルトは`256`です。 +* `--apply_lg_attn_mask` – CLIP-L/CLIP-Gの出力にパディング用のマスクを適用します。 +* `--apply_t5_attn_mask` – T5-XXLの出力にパディング用のマスクを適用します。 +* `--clip_l_dropout_rate`, `--clip_g_dropout_rate`, `--t5_dropout_rate` – 各Text Encoderのドロップアウト率を指定します。デフォルトは`0.0`です。 +* `--pos_emb_random_crop_rate=` **[SD3.5向け]** – Positional Embeddingにランダムクロップを適用する確率を指定します。 +* `--enable_scaled_pos_embed` **[SD3.5向け][実験的機能]** – マルチ解像度学習時に解像度に応じてPositional Embeddingをスケーリングします。 +* `--training_shift=` – タイムステップ分布を調整するためのシフト値です。デフォルトは`1.0`です。 +* `--weighting_scheme=` – タイムステップに応じた損失の重み付け方法を指定します。デフォルトは`uniform`です。 +* `--logit_mean`, `--logit_std`, `--mode_scale` – `logit_normal`または`mode`使用時のパラメータです。 #### メモリ・速度関連 -* `--blocks_to_swap=` **[実験的機能]** - * VRAM使用量を削減するために、モデルの一部(MMDiTのTransformerブロック)をCPUとGPU間でスワップする設定です。スワップするブロック数を整数で指定します(例: `32`)。値を大きくするとVRAM使用量は減りますが、学習速度は低下します。GPUのVRAM容量に応じて調整してください。`gradient_checkpointing`と併用可能です。 - * `--cpu_offload_checkpointing`とは併用できません。 +* `--blocks_to_swap=` **[実験的機能]** – TransformerブロックをCPUとGPUでスワップしてVRAMを節約します。`--cpu_offload_checkpointing`とは併用できません。 #### 非互換・非推奨の引数 -* `--v2`, `--v_parameterization`, `--clip_skip`: Stable Diffusion v1/v2特有の引数のため、SD3/3.5学習では使用されません。 +* `--v2`, `--v_parameterization`, `--clip_skip` – Stable Diffusion v1/v2向けの引数のため、SD3/3.5学習では使用されません。 +
-### 4.2. 学習の開始 +### 4.2. Starting Training / 学習の開始 +After setting the required arguments, run the command to begin training. The overall flow and how to check logs are the same as in the [train_network.py guide](train_network.md#32-starting-the-training--学習の開始). + +## 5. Using the Trained Model / 学習済みモデルの利用 + +When training finishes, a LoRA model file (e.g. `my_sd3_lora.safetensors`) is saved in the directory specified by `output_dir`. Use this file with inference environments that support SD3/3.5, such as ComfyUI. + +## 6. Others / その他 + +`sd3_train_network.py` shares many features with `train_network.py`, such as sample image generation (`--sample_prompts`, etc.) and detailed optimizer settings. For these, see the [train_network.py guide](train_network.md#5-other-features--その他の機能) or run `python sd3_train_network.py --help`. + +
+日本語 必要な引数を設定し、コマンドを実行すると学習が開始されます。基本的な流れやログの確認方法は[`train_network.py`のガイド](train_network.md#32-starting-the-training--学習の開始)と同様です。 -## 5. 学習済みモデルの利用 - 学習が完了すると、指定した`output_dir`にLoRAモデルファイル(例: `my_sd3_lora.safetensors`)が保存されます。このファイルは、SD3/3.5モデルに対応した推論環境(例: ComfyUIなど)で使用できます。 -## 6. その他 - `sd3_train_network.py`には、サンプル画像の生成 (`--sample_prompts`など) や詳細なオプティマイザ設定など、`train_network.py`と共通の機能も多く存在します。これらについては、[`train_network.py`のガイド](train_network.md#5-other-features--その他の機能)やスクリプトのヘルプ (`python sd3_train_network.py --help`) を参照してください。 +
diff --git a/docs/sdxl_train_network_advanced.md b/docs/sdxl_train_network_advanced.md index a736f0b3..0d4747b6 100644 --- a/docs/sdxl_train_network_advanced.md +++ b/docs/sdxl_train_network_advanced.md @@ -1,4 +1,86 @@ -ステータス:確認中 +Status: under review + +# Advanced Settings: Detailed Guide for SDXL LoRA Training Script `sdxl_train_network.py` / 高度な設定: SDXL LoRA学習スクリプト `sdxl_train_network.py` 詳細ガイド + +This document describes the advanced options available when training LoRA models for SDXL (Stable Diffusion XL) with `sdxl_train_network.py` in the `sd-scripts` repository. For the basics, please read [How to Use the LoRA Training Script `train_network.py`](train_network.md) and [How to Use the SDXL LoRA Training Script `sdxl_train_network.py`](sdxl_train_network.md). + +This guide targets experienced users who want to fine tune settings in detail. + +**Prerequisites:** + +* You have cloned the `sd-scripts` repository and prepared a Python environment. +* A training dataset and its `.toml` configuration are ready (see the dataset configuration guide). +* You are familiar with running basic LoRA training commands. + +## 1. Command Line Options / コマンドライン引数 詳細解説 + +`sdxl_train_network.py` inherits the functionality of `train_network.py` and adds SDXL-specific features. Major options are grouped and explained below. For common arguments, see the other guides mentioned above. + +### 1.1. Model Loading + +* `--pretrained_model_name_or_path=""` (required): specify the base SDXL model. Supports a Hugging Face model ID, a local Diffusers directory or a `.safetensors` file. +* `--vae=""`: optionally use a different VAE. +* `--no_half_vae`: keep the VAE in float32 even with fp16/bf16 training. +* `--fp8_base` / `--fp8_base_unet`: **experimental** load the base model or just the U-Net in FP8 to reduce VRAM (requires PyTorch 2.1+). + +### 1.2. Dataset Settings + +* `--dataset_config=""`: specify a `.toml` dataset config. High resolution data and aspect ratio buckets are common for SDXL. Bucket resolution steps must be multiples of 32. + +### 1.3. Output and Saving + +Options match `train_network.py`: + +* `--output_dir`, `--output_name` (both required) +* `--save_model_as` (recommended `safetensors`) +* `--save_precision`, `--save_every_n_epochs`, `--save_every_n_steps` +* `--save_last_n_epochs`, `--save_last_n_steps` +* `--save_state`, `--save_state_on_train_end`, `--save_last_n_epochs_state`, `--save_last_n_steps_state` +* `--no_metadata` +* `--save_state_to_huggingface` and related options + +### 1.4. Network Parameters (LoRA) + +* `--network_module=networks.lora` and `--network_dim` (required) +* `--network_alpha`, `--network_dropout` +* `--network_args` allows advanced settings such as block-wise dims/alphas and LoRA+ options +* `--network_train_unet_only` / `--network_train_text_encoder_only` +* `--network_weights` and `--dim_from_weights` + +### 1.5. Training Parameters + +Includes options for learning rate, optimizer, scheduler, mixed precision, gradient accumulation, gradient checkpointing, fused backward pass, resume, and more. See `--help` for details. + +### 1.6. Caching + +Options to cache latents or text encoder outputs in memory or on disk to speed up training. + +### 1.7. Sample Image Generation + +Options to generate sample images periodically during training. + +### 1.8. Logging & Tracking + +TensorBoard and wandb logging related options. + +### 1.9. Regularization and Advanced Techniques + +Various options such as noise offset, multires noise, input perturbation, min-SNR weighting, loss type selection, and masked loss. + +### 1.10. Distributed Training and Others + +General options like random seed, max token length, clip skip, lowram/highvram, data loader workers, config files, and Accelerate/DeepSpeed settings. + +## 2. Other Tips / その他のTips + +Hints on reducing VRAM usage, appropriate learning rates, training time considerations and troubleshooting. + +## 3. Conclusion / おわりに + +`sdxl_train_network.py` offers many options to customize SDXL LoRA training. Refer to `--help`, other documents and the source code for further details. + +
+日本語 --- @@ -257,4 +339,7 @@ SDXLは計算コストが高いため、キャッシュ機能が効果的です 不明な点や詳細については、各スクリプトの `--help` オプションや、リポジトリ内の他のドキュメント、実装コード自体を参照してください。 ---- \ No newline at end of file +--- + + +
From 08aed008eb947ca33a53007758ca619aec82fed3 Mon Sep 17 00:00:00 2001 From: Kohya S Date: Sat, 17 May 2025 14:42:19 +0900 Subject: [PATCH 6/9] doc: update FLUX.1 for newer features from README.md --- docs/flux_train_network.md | 112 +++++++++++++++++++++++++++++++++++++ 1 file changed, 112 insertions(+) diff --git a/docs/flux_train_network.md b/docs/flux_train_network.md index 4d7c2d46..2b7ff749 100644 --- a/docs/flux_train_network.md +++ b/docs/flux_train_network.md @@ -252,6 +252,15 @@ FLUX.1モデルは比較的大きなモデルであるため、十分なVRAMを - **T5XXLのfp8形式の使用**: 10GB未満のVRAMを持つGPUでは、T5XXLのfp8形式チェックポイントの使用を推奨します。[comfyanonymous/flux_text_encoders](https://huggingface.co/comfyanonymous/flux_text_encoders)から`t5xxl_fp8_e4m3fn.safetensors`をダウンロードできます(`scaled`なしで使用してください)。 +- **FP8/FP16 混合学習 [実験的機能]**: + `--fp8_base_unet` オプションを指定すると、FLUX.1モデル本体をFP8形式で学習し、Text Encoder (CLIP-L/T5XXL) をBF16/FP16形式で学習できます。これにより、さらにVRAM使用量を削減できる可能性があります。このオプションを指定すると、`--fp8_base` オプションも自動的に有効になります。 + +- **`pytorch-optimizer` の利用**: + `pytorch-optimizer` ライブラリに含まれる様々なオプティマイザを使用できます。`requirements.txt` に追加されているため、別途インストールは不要です。 + 例えば、CAME オプティマイザを使用する場合は以下のように指定します。 + ```bash + --optimizer_type "pytorch_optimizer.CAME" --optimizer_args "weight_decay=0.01" + ## 2. FLUX.1 LoRA学習の重要な設定オプション FLUX.1の学習には多くの未知の点があり、いくつかの設定は引数で指定できます。以下に重要な引数とその説明を示します。 @@ -266,6 +275,27 @@ FLUX.1の学習には多くの未知の点があり、いくつかの設定は - `shift`:正規分布乱数のシグモイド値をシフト - `flux_shift`:解像度に応じて正規分布乱数のシグモイド値をシフト(FLUX.1 dev推論と同様)。この設定では`--discrete_flow_shift`は無視されます。 + +#### タイムステップ分布の可視化 + +`--timestep_sampling`, `--sigmoid_scale`, `--discrete_flow_shift` の組み合わせによって、学習中にサンプリングされるタイムステップの分布が変化します。以下にいくつかの例を示します。 + +* `--timestep_sampling shift` と `--discrete_flow_shift` の効果 (`--sigmoid_scale` はデフォルトの1.0): + ![Figure_2](https://github.com/user-attachments/assets/d9de42f9-f17d-40da-b88d-d964402569c6) + +* `--timestep_sampling sigmoid` と `--timestep_sampling uniform` の比較 (`--discrete_flow_shift` は無視される): + ![Figure_3](https://github.com/user-attachments/assets/27029009-1f5d-4dc0-bb24-13d02ac4fdad) + +* `--timestep_sampling sigmoid` と `--sigmoid_scale` の効果 (`--discrete_flow_shift` は無視される): + ![Figure_4](https://github.com/user-attachments/assets/08a2267c-e47e-48b7-826e-f9a080787cdc) + +#### AI Toolkit 設定との比較 + +[Ostris氏のAI Toolkit](https://github.com/ostris/ai-toolkit) で使用されている設定は、概ね以下のオプションに相当すると考えられます。 +``` +--timestep_sampling sigmoid --model_prediction_type raw --guidance_scale 1.0 +``` + ### 2.2 モデル予測の処理方法 `--model_prediction_type`オプションで、モデルの予測をどのように解釈し処理するかを指定できます: @@ -283,6 +313,37 @@ FLUX.1の学習には多くの未知の点があり、いくつかの設定は ガイダンススケールについて:FLUX.1 dev版は特定のガイダンススケール値で蒸留されていますが、学習時には`--guidance_scale 1.0`を指定してガイダンススケールを無効化することを推奨します。 + +### 2.4 T5 Attention Mask の適用 + +`--apply_t5_attn_mask` オプションを指定すると、T5XXL Text Encoder の学習および推論時に Attention Mask が適用されます。 + +Attention Maskに対応した推論環境が限られるため、このオプションは推奨されません。 + +### 2.5 IP ノイズガンマ + +`--ip_noise_gamma` および `--ip_noise_gamma_random_strength` オプションを使用することで、学習時に Input Perturbation ノイズのガンマ値を調整できます。詳細は Stable Diffusion 3 の学習オプションを参照してください。 + +### 2.6 LoRA-GGPO サポート + +LoRA-GGPO (Gradient Group Proportion Optimizer) を使用できます。これは LoRA の学習を安定化させるための手法です。以下の `network_args` を指定して有効化します。ハイパーパラメータ (`ggpo_sigma`, `ggpo_beta`) は調整が必要です。 + +```bash +--network_args "ggpo_sigma=0.03" "ggpo_beta=0.01" +``` +TOMLファイルで指定する場合: +```toml +network_args = ["ggpo_sigma=0.03", "ggpo_beta=0.01"] +``` + +### 2.7 Q/K/V 射影層の分割 [実験的機能] + +`--network_args "split_qkv=True"` を指定することで、Attention層内の Q/K/V (および SingleStreamBlock の Text) 射影層を個別に分割し、それぞれに LoRA を適用できます。 + +**技術的詳細:** +FLUX.1 の元々の実装では、Q/K/V (および Text) の射影層は一つに結合されています。ここに LoRA を適用すると、一つの大きな LoRA モジュールが適用されます。一方、Diffusers の実装ではこれらの射影層は分離されており、それぞれに小さな LoRA モジュールが適用されます。このオプションは後者の挙動を模倣します。 +保存される LoRA モデルの互換性は維持されますが、内部的には分割された LoRA の重みを結合して保存するため、ゼロ要素が多くなりモデルサイズが大きくなる可能性があります。`convert_flux_lora.py` スクリプトを使用して Diffusers (AI-Toolkit) 形式に変換すると、サイズが削減されます。 + ## 3. 各層に対するランク指定 FLUX.1の各層に対して異なるランク(network_dim)を指定できます。これにより、特定の層に対してLoRAの効果を強調したり、無効化したりできます。 @@ -395,3 +456,54 @@ resolution = [512, 512] ``` 各解像度セクションの`[[datasets.subsets]]`部分は、データセットディレクトリを定義します。各解像度に対して同じディレクトリを指定してください。 + +## 7. 検証 (Validation) + +学習中に検証データセットを使用して損失 (Validation Loss) を計算し、モデルの汎化性能を評価できます。 + +検証を設定するには、データセット設定 TOML ファイルに `[validation]` セクションを追加します。設定方法は学習データセットと同様ですが、`num_repeats` は通常 1 に設定します。 + +```toml +# ... (学習データセットの設定) ... + +[validation] +batch_size = 1 +enable_bucket = true +resolution = [1024, 1024] # 検証に使用する解像度 + + [[validation.subsets]] + image_dir = "検証用画像ディレクトリへのパス" + num_repeats = 1 + caption_extension = ".txt" + # ... 他の検証データセット固有の設定 ... +``` + +**注意点:** + +* 検証損失の計算は、固定されたタイムステップサンプリングと乱数シードで行われます。これにより、ランダム性による損失の変動を抑え、より安定した評価が可能になります。 +* 現在のところ、`--blocks_to_swap` オプションを使用している場合、または Schedule-Free オプティマイザ (`AdamWScheduleFree`, `RAdamScheduleFree`, `ProdigyScheduleFree`) を使用している場合は、検証損失はサポートされていません。 + +## 8. データセット関連の追加オプション + +### 8.1 リサイズ時の補間方法指定 + +データセットの画像を学習解像度にリサイズする際の補間方法を指定できます。データセット設定 TOML ファイルの `[[datasets]]` セクションまたは `[general]` セクションで `interpolation_type` を指定します。 + +利用可能な値: `bicubic` (デフォルト), `bilinear`, `lanczos`, `nearest`, `area` + +```toml +[[datasets]] +resolution = [1024, 1024] +enable_bucket = true +interpolation_type = "lanczos" # 例: Lanczos補間を使用 +# ... +``` + +## 9. 関連ツール + +`flux_train_network.py` で学習したモデルや、学習プロセスに役立つ関連スクリプトが提供されています。 + +* **`networks/flux_extract_lora.py`**: 学習済みモデルとベースモデルの差分から LoRA モデルを抽出します。 +* **`convert_flux_lora.py`**: 学習した LoRA モデルを Diffusers (AI-Toolkit) 形式など、他の形式に変換します。Q/K/V分割オプションで学習した場合、このスクリプトで変換するとモデルサイズを削減できます。 +* **`networks/flux_merge_lora.py`**: 学習した LoRA モデルを FLUX.1 ベースモデルにマージします。 +* **`flux_minimal_inference.py`**: 学習した LoRA モデルを適用して画像を生成するためのシンプルな推論スクリプトです。 From e7e371c9ce0d764d8761f0cbc8aa9a0ebd180d72 Mon Sep 17 00:00:00 2001 From: Kohya S Date: Sat, 17 May 2025 15:06:00 +0900 Subject: [PATCH 7/9] doc: update English translation for advanced SDXL LoRA training --- docs/sdxl_train_network_advanced.md | 129 +++++++++++++++++++++++----- 1 file changed, 106 insertions(+), 23 deletions(-) diff --git a/docs/sdxl_train_network_advanced.md b/docs/sdxl_train_network_advanced.md index 0d4747b6..39844c98 100644 --- a/docs/sdxl_train_network_advanced.md +++ b/docs/sdxl_train_network_advanced.md @@ -18,62 +18,145 @@ This guide targets experienced users who want to fine tune settings in detail. ### 1.1. Model Loading -* `--pretrained_model_name_or_path=""` (required): specify the base SDXL model. Supports a Hugging Face model ID, a local Diffusers directory or a `.safetensors` file. -* `--vae=""`: optionally use a different VAE. -* `--no_half_vae`: keep the VAE in float32 even with fp16/bf16 training. -* `--fp8_base` / `--fp8_base_unet`: **experimental** load the base model or just the U-Net in FP8 to reduce VRAM (requires PyTorch 2.1+). +* `--pretrained_model_name_or_path=\"\"` **[Required]**: specify the base SDXL model. Supports a Hugging Face model ID, a local Diffusers directory or a `.safetensors` file. +* `--vae=\"\"`: optionally use a different VAE. Specify when using a VAE other than the one included in the SDXL model. Can specify `.ckpt` or `.safetensors` files. +* `--no_half_vae`: keep the VAE in float32 even with fp16/bf16 training. The VAE for SDXL can become unstable with `float16`, so it is recommended to enable this when `fp16` is specified. Usually unnecessary for `bf16`. +* `--fp8_base` / `--fp8_base_unet`: **Experimental**: load the base model (U-Net, Text Encoder) or just the U-Net in FP8 to reduce VRAM (requires PyTorch 2.1+). For details, refer to the relevant section in TODO add document later (this is an SD3 explanation but also applies to SDXL). ### 1.2. Dataset Settings -* `--dataset_config=""`: specify a `.toml` dataset config. High resolution data and aspect ratio buckets are common for SDXL. Bucket resolution steps must be multiples of 32. +* `--dataset_config=\"\"`: specify a `.toml` dataset config. High resolution data and aspect ratio buckets (specify `enable_bucket = true` in `.toml`) are common for SDXL. The resolution steps for aspect ratio buckets (`bucket_reso_steps`) must be multiples of 32 for SDXL. For details on writing `.toml` files, refer to the [Dataset Configuration Guide](link/to/dataset/config/doc). ### 1.3. Output and Saving Options match `train_network.py`: * `--output_dir`, `--output_name` (both required) -* `--save_model_as` (recommended `safetensors`) -* `--save_precision`, `--save_every_n_epochs`, `--save_every_n_steps` -* `--save_last_n_epochs`, `--save_last_n_steps` -* `--save_state`, `--save_state_on_train_end`, `--save_last_n_epochs_state`, `--save_last_n_steps_state` -* `--no_metadata` -* `--save_state_to_huggingface` and related options +* `--save_model_as` (recommended `safetensors`), `ckpt`, `pt`, `diffusers`, `diffusers_safetensors` +* `--save_precision=\"fp16\"`, `\"bf16\"`, `\"float\"`: Specifies the precision for saving the model. If not specified, the model is saved with the training precision (`fp16`, `bf16`, etc.). +* `--save_every_n_epochs=N`, `--save_every_n_steps=N`: Saves the model every N epochs/steps. +* `--save_last_n_epochs=M`, `--save_last_n_steps=M`: When saving at every epoch/step, only the latest M files are kept, and older ones are deleted. +* `--save_state`, `--save_state_on_train_end`: Saves the training state (`state`), including Optimizer status, etc., when saving the model or at the end of training. Required for resuming training with the `--resume` option. +* `--save_last_n_epochs_state=M`, `--save_last_n_steps_state=M`: Limits the number of saved `state` files to M. Overrides the `--save_last_n_epochs/steps` specification. +* `--no_metadata`: Does not save metadata to the output model. +* `--save_state_to_huggingface` and related options (e.g., `--huggingface_repo_id`): Options related to uploading models and states to Hugging Face Hub. See TODO add document for details. ### 1.4. Network Parameters (LoRA) -* `--network_module=networks.lora` and `--network_dim` (required) -* `--network_alpha`, `--network_dropout` -* `--network_args` allows advanced settings such as block-wise dims/alphas and LoRA+ options -* `--network_train_unet_only` / `--network_train_text_encoder_only` -* `--network_weights` and `--dim_from_weights` +* `--network_module=networks.lora` **[Required]** +* `--network_dim=N` **[Required]**: Specifies the rank (dimensionality) of LoRA. For SDXL, values like 32 or 64 are often tried, but adjustment is necessary depending on the dataset and purpose. +* `--network_alpha=M`: LoRA alpha value. Generally around half of `network_dim` or the same value as `network_dim`. Default is 1. +* `--network_dropout=P`: Dropout rate (0.0-1.0) within LoRA modules. Can be effective in suppressing overfitting. Default is None (no dropout). +* `--network_args ...`: Allows advanced settings by specifying additional arguments to the network module in `key=value` format. For LoRA, the following advanced settings are available: + * **Block-wise dimensions/alphas:** + * Allows specifying different `dim` and `alpha` for each block of the U-Net. This enables adjustments to strengthen or weaken the influence of specific layers. + * `block_dims`: Comma-separated dims for Linear and Conv2d 1x1 layers in U-Net (23 values for SDXL). + * `block_alphas`: Comma-separated alpha values corresponding to the above. + * `conv_block_dims`: Comma-separated dims for Conv2d 3x3 layers in U-Net. + * `conv_block_alphas`: Comma-separated alpha values corresponding to the above. + * Blocks not specified will use values from `--network_dim`/`--network_alpha` or `--conv_dim`/`--conv_alpha` (if they exist). + * For details, refer to [Block-wise learning rate for LoRA](train_network.md#lora-の階層別学習率) (in train_network.md, applicable to SDXL) and the implementation ([lora.py](lora.py)). + * **LoRA+:** + * `loraplus_lr_ratio=R`: Sets the learning rate of LoRA's upward weights (UP) to R times the learning rate of downward weights (DOWN). Expected to improve learning speed. Paper recommends 16. + * `loraplus_unet_lr_ratio=RU`: Specifies the LoRA+ learning rate ratio for the U-Net part individually. + * `loraplus_text_encoder_lr_ratio=RT`: Specifies the LoRA+ learning rate ratio for the Text Encoder part individually (multiplied by the learning rates specified with `--text_encoder_lr1`, `--text_encoder_lr2`). + * For details, refer to [README](../README.md#jan-17-2025--2025-01-17-version-090) and the implementation ([lora.py](lora.py)). +* `--network_train_unet_only`: Trains only the LoRA modules of the U-Net. Specify this if not training Text Encoders. Required when using `--cache_text_encoder_outputs`. +* `--network_train_text_encoder_only`: Trains only the LoRA modules of the Text Encoders. Specify this if not training the U-Net. +* `--network_weights=\"\"`: Starts training by loading pre-trained LoRA weights. Used for fine-tuning or resuming training. The difference from `--resume` is that this option only loads LoRA module weights, while `--resume` also restores Optimizer state, step count, etc. +* `--dim_from_weights`: Automatically reads the LoRA dimension (`dim`) from the weight file specified by `--network_weights`. Specification of `--network_dim` becomes unnecessary. ### 1.5. Training Parameters -Includes options for learning rate, optimizer, scheduler, mixed precision, gradient accumulation, gradient checkpointing, fused backward pass, resume, and more. See `--help` for details. +* `--learning_rate=LR`: Sets the overall learning rate. This becomes the default value for each module (`unet_lr`, `text_encoder_lr1`, `text_encoder_lr2`). Values like `1e-3` or `1e-4` are often tried. +* `--unet_lr=LR_U`: Learning rate for the LoRA module of the U-Net part. +* `--text_encoder_lr1=LR_TE1`: Learning rate for the LoRA module of Text Encoder 1 (OpenCLIP ViT-G/14). Usually, a smaller value than U-Net (e.g., `1e-5`, `2e-5`) is recommended. +* `--text_encoder_lr2=LR_TE2`: Learning rate for the LoRA module of Text Encoder 2 (CLIP ViT-L/14). Usually, a smaller value than U-Net (e.g., `1e-5`, `2e-5`) is recommended. +* `--optimizer_type=\"...\"`: Specifies the optimizer to use. Options include `AdamW8bit` (memory-efficient, common), `Adafactor` (even more memory-efficient, proven in SDXL full model training), `Lion`, `DAdaptation`, `Prodigy`, etc. Each optimizer may require additional arguments (see `--optimizer_args`). `AdamW8bit` or `PagedAdamW8bit` (requires `bitsandbytes`) are common. `Adafactor` is memory-efficient but slightly complex to configure (relative step (`relative_step=True`) recommended, `adafactor` learning rate scheduler recommended). `DAdaptation`, `Prodigy` have automatic learning rate adjustment but cannot be used with LoRA+. Specify a learning rate around `1.0`. For details, see the `get_optimizer` function in [train_util.py](train_util.py). +* `--optimizer_args ...`: Specifies additional arguments to the optimizer in `key=value` format (e.g., `\"weight_decay=0.01\"` `\"betas=0.9,0.999\"`). +* `--lr_scheduler=\"...\"`: Specifies the learning rate scheduler. Options include `constant` (no change), `cosine` (cosine curve), `linear` (linear decay), `constant_with_warmup` (constant with warmup), `cosine_with_restarts`, etc. `constant`, `cosine`, and `constant_with_warmup` are commonly used. Some schedulers require additional arguments (see `--lr_scheduler_args`). If using optimizers with auto LR adjustment like `DAdaptation` or `Prodigy`, a scheduler is not needed (`constant` should be specified). +* `--lr_warmup_steps=N`: Number of warmup steps for the learning rate scheduler. The learning rate gradually increases during this period at the start of training. If N < 1, it's interpreted as a fraction of total steps. +* `--lr_scheduler_num_cycles=N` / `--lr_scheduler_power=P`: Parameters for specific schedulers (`cosine_with_restarts`, `polynomial`). +* `--max_train_steps=N` / `--max_train_epochs=N`: Specifies the total number of training steps or epochs. Epoch specification takes precedence. +* `--mixed_precision=\"bf16\"` / `\"fp16\"` / `\"no\"`: Mixed precision training settings. For SDXL, using `bf16` (if GPU supports it) or `fp16` is strongly recommended. Reduces VRAM usage and improves training speed. +* `--full_fp16` / `--full_bf16`: Performs gradient calculations entirely in half-precision/bf16. Can further reduce VRAM usage but may affect training stability. Use if VRAM is critically low. +* `--gradient_accumulation_steps=N`: Accumulates gradients for N steps before updating the optimizer. Effectively increases the batch size to `train_batch_size * N`, achieving the effect of a larger batch size with less VRAM. Default is 1. +* `--max_grad_norm=N`: Gradient clipping threshold. Clips gradients if their norm exceeds N. Default is 1.0. `0` disables it. +* `--gradient_checkpointing`: Significantly reduces memory usage but slightly decreases training speed. Recommended for SDXL due to high memory consumption. +* `--fused_backward_pass`: **Experimental**: Fuses gradient calculation and optimizer steps to reduce VRAM usage. Available for SDXL. Currently only supports `Adafactor` optimizer. Cannot be used with Gradient Accumulation. +* `--resume=\"\"`: Resumes training from a saved state (saved with `--save_state`). Restores optimizer state, step count, etc. ### 1.6. Caching -Options to cache latents or text encoder outputs in memory or on disk to speed up training. +Caching is effective for SDXL due to its high computational cost. + +* `--cache_latents`: Caches VAE outputs (latents) in memory. Skips VAE computation, reducing VRAM usage and speeding up training. **Note:** Image augmentations (`color_aug`, `flip_aug`, `random_crop`, etc.) will be disabled. +* `--cache_latents_to_disk`: Used with `--cache_latents` to cache to disk. Particularly effective for large datasets or multiple training runs. Caches are generated on disk during the first run and loaded from there on subsequent runs. +* `--cache_text_encoder_outputs`: Caches Text Encoder outputs in memory. Skips Text Encoder computation, reducing VRAM usage and speeding up training. **Note:** Caption augmentations (`shuffle_caption`, `caption_dropout_rate`, etc.) will be disabled. **Also, when using this option, Text Encoder LoRA modules cannot be trained (requires `--network_train_unet_only`).** +* `--cache_text_encoder_outputs_to_disk`: Used with `--cache_text_encoder_outputs` to cache to disk. +* `--skip_cache_check`: Skips validation of cache file contents. File existence is checked, and if not found, caches are generated. Usually not needed unless intentionally re-caching for debugging, etc. ### 1.7. Sample Image Generation -Options to generate sample images periodically during training. +Basic options are common with `train_network.py`. + +* `--sample_every_n_steps=N` / `--sample_every_n_epochs=N`: Generates sample images every N steps/epochs. +* `--sample_at_first`: Generates sample images before training starts. +* `--sample_prompts=\"\"`: Specifies a file (`.txt`, `.toml`, `.json`) containing prompts for sample image generation. Format follows [gen_img_diffusers.py](gen_img_diffusers.py). See [documentation](gen_img_README-ja.md) for details. +* `--sample_sampler=\"...\"`: Specifies the sampler (scheduler) for sample image generation. `euler_a`, `dpm++_2m_karras`, etc., are common. See `--help` for choices. ### 1.8. Logging & Tracking -TensorBoard and wandb logging related options. +* `--logging_dir=\"\"`: Specifies the directory for TensorBoard and other logs. If not specified, logs are not output. +* `--log_with=\"tensorboard\"` / `\"wandb\"` / `\"all\"`: Specifies the logging tool to use. If using `wandb`, `pip install wandb` is required. +* `--log_prefix=\"\"`: Specifies the prefix for subdirectory names created within `logging_dir`. +* `--wandb_api_key=\"\"` / `--wandb_run_name=\"\"`: Options for Weights & Biases (wandb). +* `--log_tracker_name` / `--log_tracker_config`: Advanced tracker configuration options. Usually not needed. +* `--log_config`: Logs the training configuration used (excluding some sensitive information) at the start of training. Helps ensure reproducibility. ### 1.9. Regularization and Advanced Techniques -Various options such as noise offset, multires noise, input perturbation, min-SNR weighting, loss type selection, and masked loss. +* `--noise_offset=N`: Enables noise offset and specifies its value. Expected to improve bias in image brightness and contrast. Recommended to enable as SDXL base models are trained with this (e.g., 0.0357). Original technical explanation [here](https://www.crosslabs.org/blog/diffusion-with-offset-noise). +* `--noise_offset_random_strength`: Randomly varies noise offset strength between 0 and the specified value. +* `--adaptive_noise_scale=N`: Adjusts noise offset based on the mean absolute value of latents. Used with `--noise_offset`. +* `--multires_noise_iterations=N` / `--multires_noise_discount=D`: Enables multi-resolution noise. Adding noise of different frequency components is expected to improve detail reproduction. Specify iteration count N (around 6-10) and discount rate D (around 0.3). Technical explanation [here](https://wandb.ai/johnowhitaker/multires_noise/reports/Multi-Resolution-Noise-for-Diffusion-Model-Training--VmlldzozNjYyOTU2). +* `--ip_noise_gamma=G` / `--ip_noise_gamma_random_strength`: Enables Input Perturbation Noise. Adds small noise to input (latents) for regularization. Specify Gamma value (around 0.1). Strength can be randomized with `random_strength`. +* `--min_snr_gamma=N`: Applies Min-SNR Weighting Strategy. Adjusts loss weights for timesteps with high noise in early training to stabilize learning. `N=5` etc. are used. +* `--scale_v_pred_loss_like_noise_pred`: In v-prediction models, scales v-prediction loss similarly to noise prediction loss. **Not typically used for SDXL** as it's not a v-prediction model. +* `--v_pred_like_loss=N`: Adds v-prediction-like loss to noise prediction models. `N` specifies its weight. **Not typically used for SDXL**. +* `--debiased_estimation_loss`: Calculates loss using Debiased Estimation. Similar purpose to Min-SNR but a different approach. +* `--loss_type=\"l1\"` / `\"l2\"` / `\"huber\"` / `\"smooth_l1\"`: Specifies the loss function. Default is `l2` (MSE). `huber` and `smooth_l1` are robust to outliers. +* `--huber_schedule=\"constant\"` / `\"exponential\"` / `\"snr\"`: Scheduling method when using `huber` or `smooth_l1` loss. `snr` is recommended. +* `--huber_c=C` / `--huber_scale=S`: Parameters for `huber` or `smooth_l1` loss. +* `--masked_loss`: Limits loss calculation area based on a mask image. Requires specifying mask images (black and white) in `conditioning_data_dir` in dataset settings. See [About Masked Loss](masked_loss_README.md) for details. ### 1.10. Distributed Training and Others -General options like random seed, max token length, clip skip, lowram/highvram, data loader workers, config files, and Accelerate/DeepSpeed settings. +* `--seed=N`: Specifies the random seed. Set this to ensure training reproducibility. +* `--max_token_length=N` (`75`, `150`, `225`): Maximum token length processed by Text Encoders. For SDXL, typically `75` (default), `150`, or `225`. Longer lengths can handle more complex prompts but increase VRAM usage. +* `--clip_skip=N`: Uses the output from N layers skipped from the final layer of Text Encoders. **Not typically used for SDXL**. +* `--lowram` / `--highvram`: Options for memory usage optimization. `--lowram` is for environments like Colab where RAM < VRAM, `--highvram` is for environments with ample VRAM. +* `--persistent_data_loader_workers` / `--max_data_loader_n_workers=N`: Settings for DataLoader worker processes. Affects wait time between epochs and memory usage. +* `--config_file=\"\"` / `--output_config`: Options to use/output a `.toml` file instead of command line arguments. +* **Accelerate/DeepSpeed related:** (`--ddp_timeout`, `--ddp_gradient_as_bucket_view`, `--ddp_static_graph`): Detailed settings for distributed training. Accelerate settings (`accelerate config`) are usually sufficient. DeepSpeed requires separate configuration. ## 2. Other Tips / その他のTips -Hints on reducing VRAM usage, appropriate learning rates, training time considerations and troubleshooting. +* **VRAM Usage:** SDXL LoRA training requires a lot of VRAM. Even with 24GB VRAM, you might run out of memory depending on settings. Reduce VRAM usage with these settings: + * `--mixed_precision=\"bf16\"` or `\"fp16\"` (essential) + * `--gradient_checkpointing` (strongly recommended) + * `--cache_latents` / `--cache_text_encoder_outputs` (highly effective, with limitations) + * `--optimizer_type=\"AdamW8bit\"` or `\"Adafactor\"` + * Increase `--gradient_accumulation_steps` (reduce batch size) + * `--full_fp16` / `--full_bf16` (be mindful of stability) + * `--fp8_base` / `--fp8_base_unet` (experimental) + * `--fused_backward_pass` (Adafactor only, experimental) +* **Learning Rate:** Appropriate learning rates for SDXL LoRA depend on the dataset and `network_dim`/`alpha`. Starting around `1e-4` ~ `4e-5` (U-Net), `1e-5` ~ `2e-5` (Text Encoders) is common. +* **Training Time:** Training takes time due to high-resolution data and the size of the SDXL model. Using caching features and appropriate hardware is important. +* **Troubleshooting:** + * **NaN Loss:** Learning rate might be too high, mixed precision settings incorrect (e.g., `--no_half_vae` not specified with `fp16`), or dataset issues. + * **Out of Memory (OOM):** Try the VRAM reduction measures listed above. + * **Training not progressing:** Learning rate might be too low, optimizer/scheduler settings incorrect, or dataset issues. ## 3. Conclusion / おわりに From a376fec79caf6b352f4ae6144ce8b4bb42ccd8a8 Mon Sep 17 00:00:00 2001 From: Kohya S Date: Sat, 24 May 2025 18:48:54 +0900 Subject: [PATCH 8/9] doc: add comprehensive README for image generation script with usage examples and options --- docs/gen_img_README.md | 560 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 560 insertions(+) create mode 100644 docs/gen_img_README.md diff --git a/docs/gen_img_README.md b/docs/gen_img_README.md new file mode 100644 index 00000000..fd4a8290 --- /dev/null +++ b/docs/gen_img_README.md @@ -0,0 +1,560 @@ + +This is an inference (image generation) script that supports SD 1.x and 2.x models, LoRA trained with this repository, ControlNet (only v1.0 has been confirmed to work), etc. It is used from the command line. + +# Overview + +* Inference (image generation) script. +* Supports SD 1.x and 2.x (base/v-parameterization) models. +* Supports txt2img, img2img, and inpainting. +* Supports interactive mode, prompt reading from files, and continuous generation. +* The number of images generated per prompt line can be specified. +* The total number of repetitions can be specified. +* Supports not only `fp16` but also `bf16`. +* Supports xformers for high-speed generation. + * Although xformers are used for memory-saving generation, it is not as optimized as Automatic 1111's Web UI, so it uses about 6GB of VRAM for 512*512 image generation. +* Extension of prompts to 225 tokens. Supports negative prompts and weighting. +* Supports various samplers from Diffusers (fewer samplers than Web UI). +* Supports clip skip (uses the output of the nth layer from the end) of Text Encoder. +* Separate loading of VAE. +* Supports CLIP Guided Stable Diffusion, VGG16 Guided Stable Diffusion, Highres. fix, and upscale. + * Highres. fix is an original implementation that has not confirmed the Web UI implementation at all, so the output results may differ. +* LoRA support. Supports application rate specification, simultaneous use of multiple LoRAs, and weight merging. + * It is not possible to specify different application rates for Text Encoder and U-Net. +* Supports Attention Couple. +* Supports ControlNet v1.0. +* Supports Deep Shrink for optimizing generation at different depths. +* Supports Gradual Latent for progressive upscaling during generation. +* Supports CLIP Vision Conditioning for img2img. +* It is not possible to switch models midway, but it can be handled by creating a batch file. +* Various personally desired features have been added. + +Since not all tests are performed when adding features, it is possible that previous features may be affected and some features may not work. Please let us know if you have any problems. + +# Basic Usage + +## Image Generation in Interactive Mode + +Enter as follows: + +```batchfile +python gen_img.py --ckpt --outdir --xformers --fp16 --interactive +``` + +Specify the model (Stable Diffusion checkpoint file or Diffusers model folder) in the `--ckpt` option and the image output destination folder in the `--outdir` option. + +Specify the use of xformers with the `--xformers` option (remove it if you do not use xformers). The `--fp16` option performs inference in fp16 (single precision). For RTX 30 series GPUs, you can also perform inference in bf16 (bfloat16) with the `--bf16` option. + +The `--interactive` option specifies interactive mode. + +If you are using Stable Diffusion 2.0 (or a model with additional training from it), add the `--v2` option. If you are using a model that uses v-parameterization (`768-v-ema.ckpt` and models with additional training from it), add `--v_parameterization` as well. + +If the `--v2` specification is incorrect, an error will occur when loading the model. If the `--v_parameterization` specification is incorrect, a brown image will be displayed. + +When `Type prompt:` is displayed, enter the prompt. + +![image](https://user-images.githubusercontent.com/52813779/235343115-f3b8ac82-456d-4aab-9724-0cc73c4534aa.png) + +*If the image is not displayed and an error occurs, headless (no screen display function) OpenCV may be installed. Install normal OpenCV with `pip install opencv-python`. Alternatively, stop image display with the `--no_preview` option. + +Select the image window and press any key to close the window and enter the next prompt. Press Ctrl+Z and then Enter in the prompt to close the script. + +## Batch Generation of Images with a Single Prompt + +Enter as follows (actually entered on one line): + +```batchfile +python gen_img.py --ckpt --outdir \ + --xformers --fp16 --images_per_prompt --prompt "" +``` + +Specify the number of images to generate per prompt with the `--images_per_prompt` option. Specify the prompt with the `--prompt` option. If it contains spaces, enclose it in double quotes. + +You can specify the batch size with the `--batch_size` option (described later). + +## Batch Generation by Reading Prompts from a File + +Enter as follows: + +```batchfile +python gen_img.py --ckpt --outdir \ + --xformers --fp16 --from_file +``` + +Specify the file containing the prompts with the `--from_file` option. Write one prompt per line. You can specify the number of images to generate per line with the `--images_per_prompt` option. + +## Using Negative Prompts and Weighting + +If you write `--n` in the prompt options (specified like `--x` in the prompt, described later), the following will be a negative prompt. + +Also, weighting with `()` and `[]`, `(xxx:1.3)`, etc., similar to AUTOMATIC1111's Web UI, is possible (the implementation is copied from Diffusers' [Long Prompt Weighting Stable Diffusion](https://github.com/huggingface/diffusers/blob/main/examples/community/README.md#long-prompt-weighting-stable-diffusion)). + +It can be specified similarly for prompt specification from the command line and prompt reading from files. + +![image](https://user-images.githubusercontent.com/52813779/235343128-e79cd768-ec59-46f5-8395-fce9bdc46208.png) + +# Main Options + +Specify from the command line. + +## Model Specification + +- `--ckpt `: Specifies the model name. The `--ckpt` option is mandatory. You can specify a Stable Diffusion checkpoint file, a Diffusers model folder, or a Hugging Face model ID. + +- `--v2`: Specify when using Stable Diffusion 2.x series models. Not required for 1.x series. + +- `--v_parameterization`: Specify when using models that use v-parameterization (`768-v-ema.ckpt` and models with additional training from it, Waifu Diffusion v1.5, etc.). + + If the `--v2` specification is incorrect, an error will occur when loading the model. If the `--v_parameterization` specification is incorrect, a brown image will be displayed. + +- `--vae`: Specifies the VAE to use. If not specified, the VAE in the model will be used. + +## Image Generation and Output + +- `--interactive`: Operates in interactive mode. Images are generated when prompts are entered. + +- `--prompt `: Specifies the prompt. If it contains spaces, enclose it in double quotes. + +- `--from_file `: Specifies the file containing the prompts. Write one prompt per line. Image size and guidance scale can be specified with prompt options (described later). + +- `--from_module `: Loads prompts from a Python module. The module should implement a `get_prompter(args, pipe, networks)` function. + +- `--W `: Specifies the width of the image. The default is `512`. + +- `--H `: Specifies the height of the image. The default is `512`. + +- `--steps `: Specifies the number of sampling steps. The default is `50`. + +- `--scale `: Specifies the unconditional guidance scale. The default is `7.5`. + +- `--sampler `: Specifies the sampler. The default is `ddim`. ddim, pndm, dpmsolver, dpmsolver+++, lms, euler, euler_a provided by Diffusers can be specified (the last three can also be specified as k_lms, k_euler, k_euler_a). + +- `--outdir `: Specifies the output destination for images. + +- `--images_per_prompt `: Specifies the number of images to generate per prompt. The default is `1`. + +- `--clip_skip `: Specifies which layer from the end of CLIP to use. If omitted, the last layer is used. + +- `--max_embeddings_multiples `: Specifies how many times the CLIP input/output length should be multiplied by the default (75). If not specified, it remains 75. For example, specifying 3 makes the input/output length 225. + +- `--negative_scale`: Specifies the guidance scale for unconditioning individually. Implemented with reference to [this article by gcem156](https://note.com/gcem156/n/ne9a53e4a6f43). + +- `--emb_normalize_mode`: Specifies the embedding normalization mode. Options are "original" (default), "abs", and "none". This affects how prompt weights are normalized. + +## Adjusting Memory Usage and Generation Speed + +- `--batch_size `: Specifies the batch size. The default is `1`. A larger batch size consumes more memory but speeds up generation. + +- `--vae_batch_size `: Specifies the VAE batch size. The default is the same as the batch size. + Since VAE consumes more memory, memory shortages may occur after denoising (after the step reaches 100%). In such cases, reduce the VAE batch size. + +- `--vae_slices `: Splits the image into slices for VAE processing to reduce VRAM usage. None (default) for no splitting. Values like 16 or 32 are recommended. Enabling this is slower but uses less VRAM. + +- `--no_half_vae`: Prevents using fp16/bf16 precision for VAE processing. Uses fp32 instead. + +- `--xformers`: Specify when using xformers. + +- `--sdpa`: Use scaled dot-product attention in PyTorch 2 for optimization. + +- `--fp16`: Performs inference in fp16 (single precision). If neither `fp16` nor `bf16` is specified, inference is performed in fp32 (single precision). + +- `--bf16`: Performs inference in bf16 (bfloat16). Can only be specified for RTX 30 series GPUs. The `--bf16` option will cause an error on GPUs other than the RTX 30 series. It seems that `bf16` is less likely to result in NaN (black image) inference results than `fp16`. + +## Using Additional Networks (LoRA, etc.) + +- `--network_module`: Specifies the additional network to use. For LoRA, specify `--network_module networks.lora`. To use multiple LoRAs, specify like `--network_module networks.lora networks.lora networks.lora`. + +- `--network_weights`: Specifies the weight file of the additional network to use. Specify like `--network_weights model.safetensors`. To use multiple LoRAs, specify like `--network_weights model1.safetensors model2.safetensors model3.safetensors`. The number of arguments should be the same as the number specified in `--network_module`. + +- `--network_mul`: Specifies how many times to multiply the weight of the additional network to use. The default is `1`. Specify like `--network_mul 0.8`. To use multiple LoRAs, specify like `--network_mul 0.4 0.5 0.7`. The number of arguments should be the same as the number specified in `--network_module`. + +- `--network_merge`: Merges the weights of the additional networks to be used in advance with the weights specified in `--network_mul`. Cannot be used simultaneously with `--network_pre_calc`. The prompt option `--am` and Regional LoRA can no longer be used, but generation will be accelerated to the same extent as when LoRA is not used. + +- `--network_pre_calc`: Calculates the weights of the additional network to be used in advance for each generation. The prompt option `--am` can be used. Generation is accelerated to the same extent as when LoRA is not used, but time is required to calculate the weights before generation, and memory usage also increases slightly. It is disabled when Regional LoRA is used. + +- `--network_regional_mask_max_color_codes`: Specifies the maximum number of color codes to use for regional masks. If not specified, masks are applied by channel. Used with Regional LoRA to control the number of regions that can be defined by colors in the mask. + +# Examples of Main Option Specifications + +The following is an example of batch generating 64 images with the same prompt and a batch size of 4. + +```batchfile +python gen_img.py --ckpt model.ckpt --outdir outputs \ + --xformers --fp16 --W 512 --H 704 --scale 12.5 --sampler k_euler_a \ + --steps 32 --batch_size 4 --images_per_prompt 64 \ + --prompt "beautiful flowers --n monochrome" +``` + +The following is an example of batch generating 10 images each for prompts written in a file, with a batch size of 4. + +```batchfile +python gen_img.py --ckpt model.ckpt --outdir outputs \ + --xformers --fp16 --W 512 --H 704 --scale 12.5 --sampler k_euler_a \ + --steps 32 --batch_size 4 --images_per_prompt 10 \ + --from_file prompts.txt +``` + +Example of using Textual Inversion (described later) and LoRA. + +```batchfile +python gen_img.py --ckpt model.safetensors \ + --scale 8 --steps 48 --outdir txt2img --xformers \ + --W 512 --H 768 --fp16 --sampler k_euler_a \ + --textual_inversion_embeddings goodembed.safetensors negprompt.pt \ + --network_module networks.lora networks.lora \ + --network_weights model1.safetensors model2.safetensors \ + --network_mul 0.4 0.8 \ + --clip_skip 2 --max_embeddings_multiples 1 \ + --batch_size 8 --images_per_prompt 1 --interactive +``` + +# Prompt Options + +In the prompt, you can specify various options from the prompt with "two hyphens + n alphabetic characters" like `--n`. It is valid whether specifying the prompt from interactive mode, command line, or file. + +Please put spaces before and after the prompt option specification `--n`. + +- `--n`: Specifies a negative prompt. + +- `--w`: Specifies the image width. Overrides the command line specification. + +- `--h`: Specifies the image height. Overrides the command line specification. + +- `--s`: Specifies the number of steps. Overrides the command line specification. + +- `--d`: Specifies the random seed for this image. If `--images_per_prompt` is specified, specify multiple seeds separated by commas, like "--d 1,2,3,4". + *For various reasons, the generated image may differ from the Web UI even with the same random seed. + +- `--l`: Specifies the guidance scale. Overrides the command line specification. + +- `--t`: Specifies the strength of img2img (described later). Overrides the command line specification. + +- `--nl`: Specifies the guidance scale for negative prompts (described later). Overrides the command line specification. + +- `--am`: Specifies the weight of the additional network. Overrides the command line specification. If using multiple additional networks, specify them separated by __commas__, like `--am 0.8,0.5,0.3`. + +- `--glt`: Specifies the timestep to start increasing the size of the latent for Gradual Latent. Overrides the command line specification. + +- `--glr`: Specifies the initial size of the latent for Gradual Latent as a ratio. Overrides the command line specification. + +- `--gls`: Specifies the ratio to increase the size of the latent for Gradual Latent. Overrides the command line specification. + +- `--gle`: Specifies the interval to increase the size of the latent for Gradual Latent. Overrides the command line specification. + +*Specifying these options may cause the batch to be executed with a size smaller than the batch size (because they cannot be generated collectively if these values are different). (You don't have to worry too much, but when reading prompts from a file and generating, arranging prompts with the same values for these options will improve efficiency.) + +Example: +``` +(masterpiece, best quality), 1girl, in shirt and plated skirt, standing at street under cherry blossoms, upper body, [from below], kind smile, looking at another, [goodembed] --n realistic, real life, (negprompt), (lowres:1.1), (worst quality:1.2), (low quality:1.1), bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, normal quality, jpeg artifacts, signature, watermark, username, blurry --w 960 --h 640 --s 28 --d 1 +``` + +![image](https://user-images.githubusercontent.com/52813779/235343446-25654172-fff4-4aaf-977a-20d262b51676.png) + +# img2img + +## Options + +- `--image_path`: Specifies the image to use for img2img. Specify like `--image_path template.png`. If a folder is specified, images in that folder will be used sequentially. + +- `--strength`: Specifies the strength of img2img. Specify like `--strength 0.8`. The default is `0.8`. + +- `--sequential_file_name`: Specifies whether to make file names sequential. If specified, the generated file names will be sequential starting from `im_000001.png`. + +- `--use_original_file_name`: If specified, the generated file name will be the same as the original file name. + +- `--clip_vision_strength`: Enables CLIP Vision Conditioning for img2img with the specified strength. Uses the CLIP Vision model to enhance conditioning from the input image. + +## Command Line Execution Example + +```batchfile +python gen_img.py --ckpt trinart_characters_it4_v1_vae_merged.ckpt \ + --outdir outputs --xformers --fp16 --scale 12.5 --sampler k_euler --steps 32 \ + --image_path template.png --strength 0.8 \ + --prompt "1girl, cowboy shot, brown hair, pony tail, brown eyes, \ + sailor school uniform, outdoors \ + --n lowres, bad anatomy, bad hands, error, missing fingers, cropped, \ + worst quality, low quality, normal quality, jpeg artifacts, (blurry), \ + hair ornament, glasses" \ + --batch_size 8 --images_per_prompt 32 +``` + +If a folder is specified in the `--image_path` option, images in that folder will be read sequentially. The number of images generated will be the number of prompts, not the number of images, so please match the number of images to img2img and the number of prompts by specifying the `--images_per_prompt` option. + +Files are read sorted by file name. Note that the sort order is string order (not `1.jpg -> 2.jpg -> 10.jpg` but `1.jpg -> 10.jpg -> 2.jpg`), so please pad the beginning with zeros (e.g., `01.jpg -> 02.jpg -> 10.jpg`). + +## Upscale using img2img + +If you specify the generated image size with the `--W` and `--H` command line options during img2img, the original image will be resized to that size before img2img. + +Also, if the original image for img2img was generated by this script, omitting the prompt will retrieve the prompt from the original image's metadata and use it as is. This allows you to perform only the 2nd stage operation of Highres. fix. + +## Inpainting during img2img + +You can specify an image and a mask image for inpainting (inpainting models are not supported, it simply performs img2img on the mask area). + +The options are as follows: + +- `--mask_image`: Specifies the mask image. Similar to `--img_path`, if a folder is specified, images in that folder will be used sequentially. + +The mask image is a grayscale image, and the white parts will be inpainted. It is recommended to gradient the boundaries to make it somewhat smooth. + +![image](https://user-images.githubusercontent.com/52813779/235343795-9eaa6d98-02ff-4f32-b089-80d1fc482453.png) + +# Other Features + +## Textual Inversion + +Specify the embeddings to use with the `--textual_inversion_embeddings` option (multiple specifications possible). By using the file name without the extension in the prompt, that embedding will be used (same usage as Web UI). It can also be used in negative prompts. + +As models, you can use Textual Inversion models trained with this repository and Textual Inversion models trained with Web UI (image embedding is not supported). + +## Extended Textual Inversion + +Specify the `--XTI_embeddings` option instead of `--textual_inversion_embeddings`. Usage is the same as `--textual_inversion_embeddings`. + +## Highres. fix + +This is a similar feature to the one in AUTOMATIC1111's Web UI (it may differ in various ways as it is an original implementation). It first generates a smaller image and then uses that image as a base for img2img to generate a large resolution image while preventing the entire image from collapsing. + +The number of steps for the 2nd stage is calculated from the values of the `--steps` and `--strength` options (`steps*strength`). + +Cannot be used with img2img. + +The following options are available: + +- `--highres_fix_scale`: Enables Highres. fix and specifies the size of the image generated in the 1st stage as a magnification. If the final output is 1024x1024 and you want to generate a 512x512 image first, specify like `--highres_fix_scale 0.5`. Please note that this is the reciprocal of the specification in Web UI. + +- `--highres_fix_steps`: Specifies the number of steps for the 1st stage image. The default is `28`. + +- `--highres_fix_save_1st`: Specifies whether to save the 1st stage image. + +- `--highres_fix_latents_upscaling`: If specified, the 1st stage image will be upscaled on a latent basis during 2nd stage image generation (only bilinear is supported). If not specified, the image will be upscaled with LANCZOS4. + +- `--highres_fix_upscaler`: Uses an arbitrary upscaler for the 2nd stage. Currently, only `--highres_fix_upscaler tools.latent_upscaler` is supported. + +- `--highres_fix_upscaler_args`: Specifies the arguments to pass to the upscaler specified with `--highres_fix_upscaler`. + For `tools.latent_upscaler`, specify the weight file like `--highres_fix_upscaler_args "weights=D:\\Work\\SD\\Models\\others\\etc\\upscaler-v1-e100-220.safetensors"`. + +- `--highres_fix_disable_control_net`: Disables ControlNet for the 2nd stage of Highres fix. By default, ControlNet is used in both stages. + +Command line example: + +```batchfile +python gen_img.py --ckpt trinart_characters_it4_v1_vae_merged.ckpt\ + --n_iter 1 --scale 7.5 --W 1024 --H 1024 --batch_size 1 --outdir ../txt2img \ + --steps 48 --sampler ddim --fp16 \ + --xformers \ + --images_per_prompt 1 --interactive \ + --highres_fix_scale 0.5 --highres_fix_steps 28 --strength 0.5 +``` + +## Deep Shrink + +Deep Shrink is a technique that optimizes the generation process by using different depths of the UNet at different timesteps. It can improve generation quality and efficiency. + +The following options are available: + +- `--ds_depth_1`: Enables Deep Shrink with this depth for the first phase. Valid values are 0 to 8. + +- `--ds_timesteps_1`: Applies Deep Shrink depth 1 until this timestep. Default is 650. + +- `--ds_depth_2`: Specifies the depth for the second phase of Deep Shrink. + +- `--ds_timesteps_2`: Applies Deep Shrink depth 2 until this timestep. Default is 650. + +- `--ds_ratio`: Specifies the ratio for downsampling in Deep Shrink. Default is 0.5. + +These parameters can also be specified through prompt options: + +- `--dsd1`: Specifies Deep Shrink depth 1 from the prompt. + +- `--dst1`: Specifies Deep Shrink timestep 1 from the prompt. + +- `--dsd2`: Specifies Deep Shrink depth 2 from the prompt. + +- `--dst2`: Specifies Deep Shrink timestep 2 from the prompt. + +- `--dsr`: Specifies Deep Shrink ratio from the prompt. + +## ControlNet + +Currently, only ControlNet 1.0 has been confirmed to work. Only Canny is supported for preprocessing. + +The following options are available: + +- `--control_net_models`: Specifies the ControlNet model file. + If multiple are specified, they will be switched and used for each step (differs from the implementation of the ControlNet extension in Web UI). Supports both diff and normal. + +- `--guide_image_path`: Specifies the hint image to use for ControlNet. Similar to `--img_path`, if a folder is specified, images in that folder will be used sequentially. For models other than Canny, please perform preprocessing beforehand. + +- `--control_net_preps`: Specifies the preprocessing for ControlNet. Multiple specifications are possible, similar to `--control_net_models`. Currently, only canny is supported. If preprocessing is not used for the target model, specify `none`. + For canny, you can specify thresholds 1 and 2 separated by `_`, like `--control_net_preps canny_63_191`. + +- `--control_net_weights`: Specifies the weight when applying ControlNet (`1.0` for normal, `0.5` for half influence). Multiple specifications are possible, similar to `--control_net_models`. + +- `--control_net_ratios`: Specifies the range of steps to apply ControlNet. If `0.5`, ControlNet is applied up to half the number of steps. Multiple specifications are possible, similar to `--control_net_models`. + +Command line example: + +```batchfile +python gen_img.py --ckpt model_ckpt --scale 8 --steps 48 --outdir txt2img --xformers \ + --W 512 --H 768 --bf16 --sampler k_euler_a \ + --control_net_models diff_control_sd15_canny.safetensors --control_net_weights 1.0 \ + --guide_image_path guide.png --control_net_ratios 1.0 --interactive +``` + +## ControlNet-LLLite + +ControlNet-LLLite is a lightweight alternative to ControlNet that can be used for similar guidance purposes. + +The following options are available: + +- `--control_net_lllite_models`: Specifies the ControlNet-LLLite model files. + +- `--control_net_multipliers`: Specifies the multiplier for ControlNet-LLLite (similar to weights). + +- `--control_net_ratios`: Specifies the ratio of steps to apply ControlNet-LLLite. + +Note that ControlNet and ControlNet-LLLite cannot be used at the same time. + +## Attention Couple + Regional LoRA + +This is a feature that allows you to divide the prompt into several parts and specify which region in the image each prompt should be applied to. There are no individual options, but it is specified with `mask_path` and the prompt. + +First, define multiple parts using ` AND ` in the prompt. Region specification can be done for the first three parts, and subsequent parts are applied to the entire image. Negative prompts are applied to the entire image. + +In the following, three parts are defined with AND. + +``` +shs 2girls, looking at viewer, smile AND bsb 2girls, looking back AND 2girls --n bad quality, worst quality +``` + +Next, prepare a mask image. The mask image is a color image, and each RGB channel corresponds to the part separated by AND in the prompt. Also, if the value of a certain channel is all 0, it is applied to the entire image. + +In the example above, the R channel corresponds to `shs 2girls, looking at viewer, smile`, the G channel to `bsb 2girls, looking back`, and the B channel to `2girls`. If you use a mask image like the following, since there is no specification for the B channel, `2girls` will be applied to the entire image. + +![image](https://user-images.githubusercontent.com/52813779/235343061-b4dc9392-3dae-4831-8347-1e9ae5054251.png) + +The mask image is specified with `--mask_path`. Currently, only one image is supported. It is automatically resized and applied to the specified image size. + +It can also be combined with ControlNet (combination with ControlNet is recommended for detailed position specification). + +If LoRA is specified, multiple LoRAs specified with `--network_weights` will correspond to each part of AND. As a current constraint, the number of LoRAs must be the same as the number of AND parts. + +## CLIP Guided Stable Diffusion + +The source code is copied and modified from [this custom pipeline](https://github.com/huggingface/diffusers/blob/main/examples/community/README.md#clip-guided-stable-diffusion) in Diffusers' Community Examples. + +In addition to the normal prompt-based generation specification, it additionally acquires the text features of the prompt with a larger CLIP and controls the generated image so that the features of the image being generated approach those text features (this is my rough understanding). Since a larger CLIP is used, VRAM usage increases considerably (it may be difficult even for 512*512 with 8GB of VRAM), and generation time also increases. + +Note that the selectable samplers are DDIM, PNDM, and LMS only. + +Specify how much to reflect the CLIP features numerically with the `--clip_guidance_scale` option. In the previous sample, it is 100, so it seems good to start around there and increase or decrease it. + +By default, the first 75 tokens of the prompt (excluding special weighting characters) are passed to CLIP. With the `--c` option in the prompt, you can specify the text to be passed to CLIP separately from the normal prompt (for example, it is thought that CLIP cannot recognize DreamBooth identifiers or model-specific words like "1girl", so text excluding them is considered good). + +Command line example: + +```batchfile +python gen_img.py --ckpt v1-5-pruned-emaonly.ckpt --n_iter 1 \ + --scale 2.5 --W 512 --H 512 --batch_size 1 --outdir ../txt2img --steps 36 \ + --sampler ddim --fp16 --opt_channels_last --xformers --images_per_prompt 1 \ + --interactive --clip_guidance_scale 100 +``` + +## CLIP Image Guided Stable Diffusion + +This is a feature that passes another image to CLIP instead of text and controls generation to approach its features. Specify the numerical value of the application amount with the `--clip_image_guidance_scale` option and the image (file or folder) to use for guidance with the `--guide_image_path` option. + +Command line example: + +```batchfile +python gen_img.py --ckpt trinart_characters_it4_v1_vae_merged.ckpt\ + --n_iter 1 --scale 7.5 --W 512 --H 512 --batch_size 1 --outdir ../txt2img \ + --steps 80 --sampler ddim --fp16 --opt_channels_last --xformers \ + --images_per_prompt 1 --interactive --clip_image_guidance_scale 100 \ + --guide_image_path YUKA160113420I9A4104_TP_V.jpg +``` + +### VGG16 Guided Stable Diffusion + +This is a feature that generates images to approach a specified image. In addition to the normal prompt-based generation specification, it additionally acquires the features of VGG16 and controls the generated image so that the image being generated approaches the specified guide image. It is recommended to use it with img2img (images tend to be blurred in normal generation). This is an original feature that reuses the mechanism of CLIP Guided Stable Diffusion. The idea is also borrowed from style transfer using VGG. + +Note that the selectable samplers are DDIM, PNDM, and LMS only. + +Specify how much to reflect the VGG16 features numerically with the `--vgg16_guidance_scale` option. From what I've tried, it seems good to start around 100 and increase or decrease it. Specify the image (file or folder) to use for guidance with the `--guide_image_path` option. + +When batch converting multiple images with img2img and using the original images as guide images, it is OK to specify the same value for `--guide_image_path` and `--image_path`. + +Command line example: + +```batchfile +python gen_img.py --ckpt wd-v1-3-full-pruned-half.ckpt \ + --n_iter 1 --scale 5.5 --steps 60 --outdir ../txt2img \ + --xformers --sampler ddim --fp16 --W 512 --H 704 \ + --batch_size 1 --images_per_prompt 1 \ + --prompt "picturesque, 1girl, solo, anime face, skirt, beautiful face \ + --n lowres, bad anatomy, bad hands, error, missing fingers, \ + cropped, worst quality, low quality, normal quality, \ + jpeg artifacts, blurry, 3d, bad face, monochrome --d 1" \ + --strength 0.8 --image_path ..\\src_image\ + --vgg16_guidance_scale 100 --guide_image_path ..\\src_image \ +``` + +You can specify the VGG16 layer number used for feature acquisition with `--vgg16_guidance_layerP` (default is 20, which is ReLU of conv4-2). It is said that upper layers express style and lower layers express content. + +![image](https://user-images.githubusercontent.com/52813779/235343813-3c1f0d7a-4fb3-4274-98e4-b92d76b551df.png) + +# Other Options + +- `--no_preview`: Does not display preview images in interactive mode. Specify this if OpenCV is not installed or if you want to check the output files directly. + +- `--n_iter`: Specifies the number of times to repeat generation. The default is 1. Specify this when you want to perform generation multiple times when reading prompts from a file. + +- `--tokenizer_cache_dir`: Specifies the cache directory for the tokenizer. (Work in progress) + +- `--seed`: Specifies the random seed. When generating one image, it is the seed for that image. When generating multiple images, it is the seed for the random numbers used to generate the seeds for each image (when generating multiple images with `--from_file`, specifying the `--seed` option will make each image have the same seed when executed multiple times). + +- `--iter_same_seed`: When there is no random seed specification in the prompt, the same seed is used for all repetitions of `--n_iter`. Used to unify and compare seeds between multiple prompts specified with `--from_file`. + +- `--shuffle_prompts`: Shuffles the order of prompts in iteration. Useful when using `--from_file` with multiple prompts. + +- `--diffusers_xformers`: Uses Diffuser's xformers. + +- `--opt_channels_last`: Arranges tensor channels last during inference. May speed up in some cases. + +- `--network_show_meta`: Displays the metadata of the additional network. + + +--- + +# About Gradual Latent + +Gradual Latent is a Hires fix that gradually increases the size of the latent. `gen_img.py`, `sdxl_gen_img.py`, and `gen_img.py` have the following options. + +- `--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. +- `--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. +- `--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. +- `--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. +- `--gradual_latent_s_noise`: Specifies the s_noise parameter for Gradual Latent. Default is 1.0. +- `--gradual_latent_unsharp_params`: Specifies unsharp mask parameters for Gradual Latent: ksize, sigma, strength, target-x (1 means True). Values like `3,0.5,0.5,1` or `3,1.0,1.0,0` are recommended. + +Each option can also be specified with prompt options, `--glt`, `--glr`, `--gls`, `--gle`. + +__Please specify `euler_a` for the sampler.__ Because the source code of the sampler is modified. It will not work with other samplers. + +It is more effective with SD 1.5. It is quite subtle with SDXL. + +# Gradual Latent について (Japanese section - kept for reference) + +latentのサイズを徐々に大きくしていくHires fixです。`gen_img.py` 、``sdxl_gen_img.py` 、`gen_img.py` に以下のオプションが追加されています。 + +- `--gradual_latent_timesteps` : latentのサイズを大きくし始めるタイムステップを指定します。デフォルトは None で、Gradual Latentを使用しません。750 くらいから始めてみてください。 +- `--gradual_latent_ratio` : latentの初期サイズを指定します。デフォルトは 0.5 で、デフォルトの latent サイズの半分のサイズから始めます。 +- `--gradual_latent_ratio_step`: latentのサイズを大きくする割合を指定します。デフォルトは 0.125 で、latentのサイズを 0.625, 0.75, 0.875, 1.0 と徐々に大きくします。 +- `--gradual_latent_ratio_every_n_steps`: latentのサイズを大きくする間隔を指定します。デフォルトは 3 で、3ステップごとに latent のサイズを大きくします。 + +それぞれのオプションは、プロンプトオプション、`--glt`、`--glr`、`--gls`、`--gle` でも指定できます。 + +サンプラーに手を加えているため、__サンプラーに `euler_a` を指定してください。__ 他のサンプラーでは動作しません。 + +SD 1.5 のほうが効果があります。SDXL ではかなり微妙です。 From c84a163b3231e97cea77292551fa8b3967d2594a Mon Sep 17 00:00:00 2001 From: Kohya S Date: Mon, 21 Jul 2025 13:40:03 +0900 Subject: [PATCH 9/9] docs: update README for documentation --- README.md | 9 +++++++++ docs/lumina_train_network.md | 2 +- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index b6365644..3ef16593 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,16 @@ If you are using DeepSpeed, please install DeepSpeed with `pip install deepspeed Jul 21, 2025: - Support for [Lumina-Image 2.0](https://github.com/Alpha-VLLM/Lumina-Image-2.0) has been added in PR [#1927](https://github.com/kohya-ss/sd-scripts/pull/1927) and [#2138](https://github.com/kohya-ss/sd-scripts/pull/2138). Special thanks to sdbds and RockerBOO for their contributions. - Please refer to the [Lumina-Image 2.0 documentation](./docs/lumina_train_network.md) for more details. +- We have started adding comprehensive training-related documentation to [docs](./docs). These documents are being created with the help of generative AI and will be updated over time. While there are still many gaps at this stage, we plan to improve them gradually. + Currently, the following documents are available: + - train_network.md + - sdxl_train_network.md + - sdxl_train_network_advanced.md + - flux_train_network.md + - sd3_train_network.md + - lumina_train_network.md + Jul 10, 2025: - [AI Coding Agents](#for-developers-using-ai-coding-agents) section is added to the README. This section provides instructions for developers using AI coding agents like Claude and Gemini to understand the project context and coding standards. diff --git a/docs/lumina_train_network.md b/docs/lumina_train_network.md index 5f2fda17..3f0548d9 100644 --- a/docs/lumina_train_network.md +++ b/docs/lumina_train_network.md @@ -6,7 +6,7 @@ This document explains how to train LoRA (Low-Rank Adaptation) models for Lumina `lumina_train_network.py` trains additional networks such as LoRA for Lumina Image 2.0 models. Lumina Image 2.0 adopts a Next-DiT (Next-generation Diffusion Transformer) architecture, which differs from previous Stable Diffusion models. It uses a single text encoder (Gemma2) and a dedicated AutoEncoder (AE). -This guide assumes you already understand the basics of LoRA training. For common usage and options, see the train_network.py guide (to be documented). Some parameters are similar to those in [`sd3_train_network.py`](sd3_train_network.md) and [`flux_train_network.py`](flux_train_network.md). +This guide assumes you already understand the basics of LoRA training. For common usage and options, see [the train_network.py guide](./train_network.md). Some parameters are similar to those in [`sd3_train_network.py`](sd3_train_network.md) and [`flux_train_network.py`](flux_train_network.md). **Prerequisites:**