> 📝 Click on the language section to expand / 蚀語をクリックしお展開 # Advanced configuration / 高床な蚭定 ## Table of contents / 目次 - [Using configuration files to specify training options](#using-configuration-files-to-specify-training-options--蚭定ファむルを䜿甚した孊習オプションの指定) - [How to specify `network_args`](#how-to-specify-network_args--network_argsの指定方法) - [LoRA+](#lora) - [Select the target modules of LoRA](#select-the-target-modules-of-lora--loraの察象モゞュヌルを遞択する) - [Save and view logs in TensorBoard format](#save-and-view-logs-in-tensorboard-format--tensorboard圢匏のログの保存ず参照) - [Save and view logs in wandb](#save-and-view-logs-in-wandb--wandbでログの保存ず参照) - [FP8 weight optimization for models](#fp8-weight-optimization-for-models--モデルの重みのfp8ぞの最適化) - [PyTorch Dynamo optimization for model training](#pytorch-dynamo-optimization-for-model-training--モデルの孊習におけるpytorch-dynamoの最適化) - [MagCache](#magcache) - [Style-Friendly SNR Sampler](#style-friendly-snr-sampler) - [Specify time step range for training](#specify-time-step-range-for-training--孊習時のタむムステップ範囲の指定) - [Timestep Bucketing for Uniform Sampling](#timestep-bucketing-for-uniform-sampling--均䞀なサンプリングのためのtimestep-bucketing) - [Schedule Free Optimizer](#schedule-free-optimizer--スケゞュヌルフリヌオプティマむザ) [Post-Hoc EMA merging for LoRA](tools.md#lora-post-hoc-ema-merging--loraのpost-hoc-emaマヌゞ) is described in the [Tools](tools.md) document. ## Using configuration files to specify training options / 蚭定ファむルを䜿甚した孊習オプションの指定 Instead of specifying all training options on the command line, you can use a `.toml` configuration file to specify them. This can make it easier to manage and reuse training configurations. Specify the configuration file with the `--config_file` option. The `.toml` extension can be omitted. ```bash accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 src/musubi_tuner/hv_train_network.py --config_file config.toml ``` The configuration file is a TOML file that can contain any of the command-line options. The file can be organized into sections for readability, but all sections are flattened when parsed, so the section names are ignored.
日本語 すべおの孊習オプションをコマンドラむンで指定する代わりに、`.toml`蚭定ファむルを䜿甚しお指定するこずができたす。これにより、孊習蚭定の管理や再利甚が容易になりたす。 `--config_file`オプションで蚭定ファむルを指定したす。`.toml`拡匵子は省略できたす。 ```bash accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 src/musubi_tuner/hv_train_network.py --config_file config.toml ``` 蚭定ファむルは、コマンドラむンオプションのいずれかを含むこずができるTOMLファむルです。ファむルは読みやすさのためにセクションに分けるこずができたすが、解析時にすべおのセクションがフラット化されるため、セクション名は無芖されたす。
### Example configuration file / 蚭定ファむルの䟋 ```toml # config.toml dit = "/path/to/dit" dataset_config = "/path/to/dataset.toml" network_module = "networks.lora" network_dim = 32 network_alpha = 16 [optimizer] optimizer_type = "AdamW" learning_rate = 1e-4 [training] max_train_epochs = 10 save_every_n_epochs = 2 mixed_precision = "bf16" [output] output_dir = "/path/to/output" output_name = "my_lora" logging_dir = "./logs" ``` All options can be specified in the top level or within sections. When parsed, the section structure is ignored and all key-value pairs are combined into a single namespace. Options specified on the command line will override those in the configuration file. ```bash # This will use the config file but override the learning_rate accelerate launch --mixed_precision bf16 src/musubi_tuner/hv_train_network.py --config_file config --learning_rate 2e-4 ```
日本語 すべおのオプションは、トップレベルたたはセクション内に指定できたす。解析時には、セクション構造は無芖され、すべおのキヌず倀のペアが単䞀のネヌムスペヌスに結合されたす。 コマンドラむンで指定されたオプションは、蚭定ファむルのオプションを䞊曞きしたす。 ```bash # 蚭定ファむルを䜿甚したすが、learning_rateを䞊曞きしたす accelerate launch --mixed_precision bf16 src/musubi_tuner/hv_train_network.py --config_file config --learning_rate 2e-4 ```
## How to specify `network_args` / `network_args`の指定方法 The `--network_args` option is an option for specifying detailed arguments to LoRA. Specify the arguments in the form of `key=value` in `--network_args`.
日本語 `--network_args`オプションは、LoRAぞの詳现な匕数を指定するためのオプションです。`--network_args`には、`key=value`の圢匏で匕数を指定したす。
### Example / 蚘述䟋 If you specify it on the command line, write as follows. / コマンドラむンで指定する堎合は以䞋のように蚘述したす。 ```bash accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 src/musubi_tuner/hv_train_network.py --dit ... --network_module networks.lora --network_dim 32 --network_args "key1=value1" "key2=value2" ... ``` If you specify it in the configuration file, write as follows. / 蚭定ファむルで指定する堎合は以䞋のように蚘述したす。 ```toml network_args = ["key1=value1", "key2=value2", ...] ``` If you specify `"verbose=True"`, detailed information of LoRA will be displayed. / `"verbose=True"`を指定するずLoRAの詳现な情報が衚瀺されたす。 ```bash --network_args "verbose=True" "key1=value1" "key2=value2" ... ``` ## LoRA+ LoRA+ is a method to improve the training speed by increasing the learning rate of the UP side (LoRA-B) of LoRA. Specify the multiplier for the learning rate. The original paper recommends 16, but adjust as needed. It seems to be good to start from around 4. For details, please refer to the [related PR of sd-scripts](https://github.com/kohya-ss/sd-scripts/pull/1233). Specify `loraplus_lr_ratio` with `--network_args`.
日本語 LoRA+は、LoRAのUP偎LoRA-Bの孊習率を䞊げるこずで孊習速床を向䞊させる手法です。孊習率に察する倍率を指定したす。元論文では16を掚奚しおいたすが、必芁に応じお調敎しおください。4皋床から始めるずよいようです。詳现は[sd-scriptsの関連PR]https://github.com/kohya-ss/sd-scripts/pull/1233)を参照しおください。 `--network_args`で`loraplus_lr_ratio`を指定したす。
### Example / 蚘述䟋 ```bash accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 src/musubi_tuner/hv_train_network.py --dit ... --network_module networks.lora --network_dim 32 --network_args "loraplus_lr_ratio=4" ... ``` ## Select the target modules of LoRA / LoRAの察象モゞュヌルを遞択する *This feature is highly experimental and the specification may change. / この機胜は特に実隓的なもので、仕様は倉曎される可胜性がありたす。* By specifying `exclude_patterns` and `include_patterns` with `--network_args`, you can select the target modules of LoRA. `exclude_patterns` excludes modules that match the specified pattern. `include_patterns` targets only modules that match the specified pattern. Specify the values as a list. For example, `"exclude_patterns=[r'.*single_blocks.*', r'.*double_blocks\.[0-9]\..*']"`. The pattern is a regular expression for the module name. The module name is in the form of `double_blocks.0.img_mod.linear` or `single_blocks.39.modulation.linear`. The regular expression is not a partial match but a complete match. The patterns are applied in the order of `exclude_patterns`→`include_patterns`. By default, the Linear layers of `img_mod`, `txt_mod`, and `modulation` of double blocks and single blocks are excluded. (`.*(img_mod|txt_mod|modulation).*` is specified.)
日本語 `--network_args`で`exclude_patterns`ず`include_patterns`を指定するこずで、LoRAの察象モゞュヌルを遞択するこずができたす。 `exclude_patterns`は、指定したパタヌンに䞀臎するモゞュヌルを陀倖したす。`include_patterns`は、指定したパタヌンに䞀臎するモゞュヌルのみを察象ずしたす。 倀は、リストで指定したす。`"exclude_patterns=[r'.*single_blocks.*', r'.*double_blocks\.[0-9]\..*']"`のようになりたす。 パタヌンは、モゞュヌル名に察する正芏衚珟です。モゞュヌル名は、たずえば`double_blocks.0.img_mod.linear`や`single_blocks.39.modulation.linear`のような圢匏です。正芏衚珟は郚分䞀臎ではなく完党䞀臎です。 パタヌンは、`exclude_patterns`→`include_patterns`の順で適甚されたす。デフォルトは、double blocksずsingle blocksのLinear局のうち、`img_mod`、`txt_mod`、`modulation`が陀倖されおいたす。 `.*(img_mod|txt_mod|modulation).*`が指定されおいたす。
### Example / 蚘述䟋 Only the modules of double blocks / double blocksのモゞュヌルのみを察象ずする堎合: ```bash --network_args "exclude_patterns=[r'.*single_blocks.*']" ``` Only the modules of single blocks from the 10th / single blocksの10番目以降のLinearモゞュヌルのみを察象ずする堎合: ```bash --network_args "exclude_patterns=[r'.*']" "include_patterns=[r'.*single_blocks\.\d{2}\.linear.*']" ``` ## Save and view logs in TensorBoard format / TensorBoard圢匏のログの保存ず参照 Specify the folder to save the logs with the `--logging_dir` option. Logs in TensorBoard format will be saved. For example, if you specify `--logging_dir=logs`, a `logs` folder will be created in the working folder, and logs will be saved in the date folder inside it. Also, if you specify the `--log_prefix` option, the specified string will be added before the date. For example, use `--logging_dir=logs --log_prefix=lora_setting1_` for identification. To view logs in TensorBoard, open another command prompt and activate the virtual environment. Then enter the following in the working folder. ```powershell tensorboard --logdir=logs ``` (tensorboard installation is required.) Then open a browser and access http://localhost:6006/ to display it.
日本語 `--logging_dir`オプションにログ保存先フォルダを指定しおください。TensorBoard圢匏のログが保存されたす。 たずえば`--logging_dir=logs`ず指定するず、䜜業フォルダにlogsフォルダが䜜成され、その䞭の日時フォルダにログが保存されたす。 たた`--log_prefix`オプションを指定するず、日時の前に指定した文字列が远加されたす。`--logging_dir=logs --log_prefix=lora_setting1_`などずしお識別甚にお䜿いください。 TensorBoardでログを確認するには、別のコマンドプロンプトを開き、仮想環境を有効にしおから、䜜業フォルダで以䞋のように入力したす。 ```powershell tensorboard --logdir=logs ``` tensorboardのむンストヌルが必芁です。 その埌ブラりザを開き、http://localhost:6006/ ぞアクセスするず衚瀺されたす。
## Save and view logs in wandb / wandbでログの保存ず参照 `--log_with wandb` option is available to save logs in wandb format. `tensorboard` or `all` is also available. The default is `tensorboard`. Specify the project name with `--log_tracker_name` when using wandb.
日本語 `--log_with wandb`オプションを指定するずwandb圢匏でログを保存するこずができたす。`tensorboard`や`all`も指定可胜です。デフォルトは`tensorboard`です。 wandbを䜿甚する堎合は、`--log_tracker_name`でプロゞェクト名を指定しおください。
## FP8 weight optimization for models / モデルの重みのFP8ぞの最適化 The `--fp8_scaled` option performs an offline optimization pass that rewrites selected Linear weights into FP8 (E4M3) with block-wise scaling. Compared with the legacy `--fp8` cast, it reduces VRAM usage while maintaining relatively high precision. From v0.2.12, block-wise scaling is supported instead of per-tensor scaling, allowing for higher precision quantization. This flow dequantizes back the weights to the FP16/BF16/FP32 weights during the forward path, and computes in FP16/BF16/FP32. The shared routines live in `src/musubi_tuner/modules/fp8_optimization_utils.py` and are wired into the Wan2.x, FramePack, FLUX.1 Kontext, and Qwen-Image pipelines (except HunyuanVideo, which `--fp8_scaled` is not supported). Acknowledgments: This idea is based on the [implementation](https://github.com/Tencent/HunyuanVideo/blob/7df4a45c7e424a3f6cd7d653a7ff1f60cddc1eb1/hyvideo/modules/fp8_optimization.py) of [HunyuanVideo](https://github.com/Tencent/HunyuanVideo). The selection of high-precision modules is referenced from the [implementation](https://github.com/tdrussell/diffusion-pipe/blob/407c04fdae1c9ab5e67b54d33bef62c3e0a8dbc7/models/wan.py) of [diffusion-pipe](https://github.com/tdrussell/diffusion-pipe). I would like to thank these repositories.
日本語 `--fp8_scaled` オプションは、察象の Linear 局の重みを、blockごずに適切な倍率でスケヌリングした FP8 (E4M3) に曞き換える前凊理を実行したす。埓来の `--fp8` による単玔なキャストず比べお、元の粟床を比范的保ったたた VRAM を削枛できたす。 v0.2.12から、テン゜ルごずのスケヌリングではなく、ブロック単䜍のスケヌリングに察応したした。これにより、より高い粟床での量子化が可胜になりたす。 forward の蚈算は、逆量子化を行なった重みで FP16/BF16 で行われたす。共通ルヌチンは `src/musubi_tuner/modules/fp8_optimization_utils.py` にあり、Wan 2.x・FramePack・FLUX.1 Kontext・Qwen-Image の各パむプラむンで利甚されたすHunyuanVideo に぀いおは `--fp8_scaled` オプションは無効です。 このアむデアは、[HunyuanVideo](https://github.com/Tencent/HunyuanVideo) の [実装](https://github.com/Tencent/HunyuanVideo/blob/7df4a45c7e424a3f6cd7d653a7ff1f60cddc1eb1/hyvideo/modules/fp8_optimization.py) に基づいおいたす。高粟床モゞュヌルの遞定は、[diffusion-pipe](https://github.com/tdrussell/diffusion-pipe) の [実装](https://github.com/tdrussell/diffusion-pipe/blob/407c04fdae1c9ab5e67b54d33bef62c3e0a8dbc7/models/wan.py) を参考にしおいたす。これらのリポゞトリに感謝したす。
### Usage summary / 䜿い方のたずめ - Inference: add `--fp8` and `--fp8_scaled` when running `wan_generate_video.py`, `fpack_generate_video.py`, `flux_kontext_generate_image.py`, or `qwen_image_generate_image.py`. HunyuanVideo continues to rely on `--fp8`/`--fp8_fast` without scaled weights. - Training: specify `--fp8_base --fp8_scaled` in `wan_train_network.py`, `fpack_train_network.py`,`flux_kontext_train_network.py` and `qwen_image_train_network.py`; the trainers enforce this pairing. - Input checkpoints must be FP16/BF16; pre-quantized FP8 weights cannot be re-optimized. - LoRA / LyCORIS weights are merged before quantization, so no additional steps are required.
日本語 - 掚論では `wan_generate_video.py`、`fpack_generate_video.py`、`flux_kontext_generate_image.py`、`qwen_image_generate_image.py` を実行する際に `--fp8` ず `--fp8_scaled` を䜵甚しおください。HunyuanVideo は匕き続き`--fp8` / `--fp8_fast` を䜿甚し、スケヌリング付き重みは未察応です。 - 孊習では `wan_train_network.py`、`fpack_train_network.py`、`flux_kontext_train_network.py` で `--fp8_base --fp8_scaled` を指定したす。 - 読み蟌むチェックポむントは FP16/BF16 である必芁がありたす。あらかじめ FP8 化された重みは再最適化できたせん。 - LoRA / LyCORIS の重みは量子化の前に自動でマヌゞされるため、远加䜜業は䞍芁です。
### Implementation highlights / 実装のポむント When `--fp8_scaled` flag is enabled, the loader loads the base weights in FP16/BF16, merges optional LoRA or LyCORIS, and then emits FP8 weights plus matching block-wise `.scale_weight` buffers for the targeted layers. The patched forward either dequantizes back to the original dtype on demand for computation. The current scripts in this repository use FP8 E4M3 format and block-wise quantization, but the implementation supports: - Implements FP8 (E4M3 or E5M2) weight quantization for Linear layers - Supports multiple quantization modes: tensor-wise, channel-wise, and block-wise quantization described below - Block-wise quantization provides better precision by using granular scaling with configurable block size (default: 64) - Reduces VRAM requirements by using 8-bit weights for storage (slightly increased compared to existing `--fp8` `--fp8_base` options) - Quantizes weights to FP8 format with appropriate scaling instead of simple cast to FP8 - Applies monkey patching to Linear layers for transparent dequantization during computation - Maintains computational precision by dequantizing to original precision (FP16/BF16) during forward pass - Preserves important weights for example norm, embedding, modulation in FP16/BF16 format (fewer exclusions than previous versions) For quantization and precision discussion, see also [Discussion #564](https://github.com/kohya-ss/musubi-tuner/discussions/564). Note: Testing for quantization other than E4M3/block-wise is limited, so please be cautious if you plan to use the code in other projects.
日本語 `--fp8_scaled` フラグを有効にするず、ロヌダヌはたずベヌスずなる重みを FP16/BF16 のたた読み蟌み、必芁に応じお LoRA や LyCORIS をマヌゞした埌、察象局の重みを FP8 の重みず、ブロックごずの `.scale_weight` バッファぞ倉換したす。forward ではこのスケヌルを䜿っお元の粟床ぞ動的に逆量子化し蚈算を行いたす。 このリポゞトリの珟圚のスクリプトでは、量子化はFP8 E4M3圢匏、ブロック単䜍量子化が甚いられおいたすが、実装ずしおは以䞋をサポヌトしおいたす - Linear局のFP8E4M3たたはE5M2重み量子化を実装 - 耇数の量子化モヌド察応テン゜ル単䜍、チャネル単䜍、ブロック単䜍量子化 - ブロック単䜍量子化は指定したブロックサむズデフォルト64での现粒床スケヌリングによりより高い粟床を提䟛 - 8ビットの重みを䜿甚するこずでVRAM䜿甚量を削枛既存の`--fp8` `--fp8_base` オプションに比べお埮増 - 単玔なFP8ぞのcastではなく、適切な倀でスケヌルしお重みをFP8圢匏に量子化 - Linear局にmonkey patchingを適甚し、蚈算時に透過的に逆量子化 - forward時に元の粟床FP16/BF16に逆量子化しお蚈算粟床を維持 - 粟床が重芁な重み、たずえばnormやembedding、modulationは、FP16/BF16のたた保持埓来バヌゞョンより陀倖察象を削枛 量子化ず粟床に぀いおは[Discussion #564](https://github.com/kohya-ss/musubi-tuner/discussions/564)も参照しおください。 ※E4M3/ブロック単䜍以倖の量子化のテストは䞍十分ですので、コヌドを他のプロゞェクトで利甚する堎合等には泚意しおください。
### Quantization modes / 量子化モヌド The current implementation supports three quantization modes: - **Block-wise quantization (default)**: Divides weight matrices into blocks of configurable size (default: 64) and calculates separate scale factors for each block. Provides the best precision but requires more memory for scale storage. - **Channel-wise quantization**: Calculates scale factors per output channel (row). Balances precision and memory usage. - **Tensor-wise quantization**: Uses a single scale factor for the entire weight tensor. Lowest memory usage but may have reduced precision for some weights. The implementation automatically falls back to simpler modes when block-wise quantization is not feasible (e.g., when weight dimensions are not divisible by block size).
日本語 珟圚の実装では3぀の量子化モヌドをサポヌトしおいたす - **ブロック単䜍量子化デフォルト**重み行列を蚭定可胜なサむズのブロックデフォルト64に分割し、各ブロックに察しお個別のスケヌル係数を蚈算したす。最高の粟床を提䟛したすが、スケヌル保存により远加メモリが必芁です。 - **チャネル単䜍量子化**出力チャネル行ごずにスケヌル係数を蚈算したす。粟床ずメモリ䜿甚量のバランスを取りたす。 - **テン゜ル単䜍量子化**重みテン゜ル党䜓に察しお単䞀のスケヌル係数を䜿甚したす。最も少ないメモリ䜿甚量ですが、䞀郚の重みで粟床が䜎䞋する堎合がありたす。 実装では、ブロック単䜍量子化が実行䞍可胜な堎合重み次元がブロックサむズで割り切れない堎合など、自動的により単玔なモヌドにフォヌルバックしたす。
## PyTorch Dynamo optimization for model training / モデルの孊習におけるPyTorch Dynamoの最適化 The PyTorch Dynamo options are now available to optimize the training process. PyTorch Dynamo is a Python-level JIT compiler designed to make unmodified PyTorch programs faster by using TorchInductor, a deep learning compiler. This integration allows for potential speedups in training while maintaining model accuracy. [PR #215](https://github.com/kohya-ss/musubi-tuner/pull/215) added this feature. Specify the `--dynamo_backend` option to enable Dynamo optimization with one of the available backends from the `DynamoBackend` enum. Additional options allow for fine-tuning the Dynamo behavior: - `--dynamo_mode`: Controls the optimization strategy - `--dynamo_fullgraph`: Enables fullgraph mode for potentially better optimization - `--dynamo_dynamic`: Enables dynamic shape handling The `--dynamo_dynamic` option has been reported to have many problems based on the validation in PR #215. ### Available options: ``` --dynamo_backend {NO, INDUCTOR, NVFUSER, CUDAGRAPHS, CUDAGRAPHS_FALLBACK, etc.} Specifies the Dynamo backend to use (default is NO, which disables Dynamo) --dynamo_mode {default, reduce-overhead, max-autotune} Specifies the optimization mode (default is 'default') - 'default': Standard optimization - 'reduce-overhead': Focuses on reducing compilation overhead - 'max-autotune': Performs extensive autotuning for potentially better performance --dynamo_fullgraph Flag to enable fullgraph mode, which attempts to capture and optimize the entire model graph --dynamo_dynamic Flag to enable dynamic shape handling for models with variable input shapes ``` ### Usage example: ```bash python src/musubi_tuner/hv_train_network.py --dynamo_backend INDUCTOR --dynamo_mode default ``` For more aggressive optimization: ```bash python src/musubi_tuner/hv_train_network.py --dynamo_backend INDUCTOR --dynamo_mode max-autotune --dynamo_fullgraph ``` Note: The best combination of options may depend on your specific model and hardware. Experimentation may be necessary to find the optimal configuration.
日本語 PyTorch Dynamoオプションが孊習プロセスを最適化するために远加されたした。PyTorch Dynamoは、TorchInductorディヌプラヌニングコンパむラを䜿甚しお、倉曎を加えるこずなくPyTorchプログラムを高速化するためのPythonレベルのJITコンパむラです。この統合により、モデルの粟床を維持しながら孊習の高速化が期埅できたす。 [PR #215](https://github.com/kohya-ss/musubi-tuner/pull/215) で远加されたした。 `--dynamo_backend`オプションを指定しお、`DynamoBackend`列挙型から利甚可胜なバック゚ンドの䞀぀を遞択するこずで、Dynamo最適化を有効にしたす。 远加のオプションにより、Dynamoの動䜜を埮調敎できたす - `--dynamo_mode`最適化戊略を制埡したす - `--dynamo_fullgraph`より良い最適化の可胜性のためにフルグラフモヌドを有効にしたす - `--dynamo_dynamic`動的圢状凊理を有効にしたす PR #215での怜蚌によるず、`--dynamo_dynamic`には問題が倚いこずが報告されおいたす。 __利甚可胜なオプション__ ``` --dynamo_backend {NO, INDUCTOR, NVFUSER, CUDAGRAPHS, CUDAGRAPHS_FALLBACK, など} 䜿甚するDynamoバック゚ンドを指定したすデフォルトはNOで、Dynamoを無効にしたす --dynamo_mode {default, reduce-overhead, max-autotune} 最適化モヌドを指定したすデフォルトは 'default' - 'default'暙準的な最適化 - 'reduce-overhead'コンパむルのオヌバヌヘッド削枛に焊点を圓おる - 'max-autotune'より良いパフォヌマンスのために広範な自動調敎を実行 --dynamo_fullgraph フルグラフモヌドを有効にするフラグ。モデルグラフ党䜓をキャプチャしお最適化しようずしたす --dynamo_dynamic 可倉入力圢状を持぀モデルのための動的圢状凊理を有効にするフラグ ``` __䜿甚䟋__ ```bash python src/musubi_tuner/hv_train_network.py --dynamo_backend INDUCTOR --dynamo_mode default ``` より積極的な最適化の堎合 ```bash python src/musubi_tuner/hv_train_network.py --dynamo_backend INDUCTOR --dynamo_mode max-autotune --dynamo_fullgraph ``` 泚意最適なオプションの組み合わせは、特定のモデルずハヌドりェアに䟝存する堎合がありたす。最適な構成を芋぀けるために実隓が必芁かもしれたせん。
## MagCache The following is quoted from the [MagCache github repository](https://github.com/Zehong-Ma/MagCache) "Magnitude-aware Cache (MagCache) for Video Diffusion Models": > We introduce Magnitude-aware Cache (MagCache), a training-free caching approach that estimates and leverages the fluctuating differences among model outputs across timesteps based on the robust magnitude observations, thereby accelerating the inference. MagCache works well for Video Diffusion Models, Image Diffusion models. We have implemented the MagCache feature in Musubi Tuner. Some of the code is based on the MagCache repository. It is available for `fpack_generate_video.py` for now. ### Usage 1. Calibrate the mag ratios - Run the inference script as normal, but with the `--magcache_calibration` option to calibrate the mag ratios. You will get a following output: ``` INFO:musubi_tuner.fpack_generate_video:Copy and paste following values to --magcache_mag_ratios argument to use them: 1.00000,1.26562,1.08594,1.02344,1.00781,1.01562,1.01562,1.03125,1.04688,1.00781,1.03125,1.00000,1.01562,1.01562,1.02344,1.01562,0.98438,1.05469,0.98438,0.97266,1.03125,0.96875,0.93359,0.95703,0.77734 ``` - It is recommended to run the calibration with your custom prompt and model. - If you inference the multi-section video, you will get the mag ratios for each section. You can use the one of the sections or average them. 2. Use the mag ratios - Run the inference script with the `--magcache_mag_ratios` option to use the mag ratios. For example: ```bash python fpack_generate_video.py --magcache_mag_ratios 1.00000,1.26562,1.08594,1.02344,1.00781,1.01562,1.01562,1.03125,1.04688,1.00781,1.03125,1.00000,1.01562,1.01562,1.02344,1.01562,0.98438,1.05469,0.98438,0.97266,1.03125,0.96875,0.93359,0.95703,0.77734 ``` - Specify `--magcache_mag_ratios 0` to use the default mag ratios from the MagCache repository. - It is recommended to use the same steps as the calibration. If the steps are different, the mag ratios is interpolated to the specified steps. - You can also specify the `--magcache_retention_ratio`, `--magcache_threshold`, and `--magcache_k` options to control the MagCache behavior. The default values are 0.2, 0.24, and 6, respectively (same as the MagCache repository). ```bash python fpack_generate_video.py --magcache_retention_ratio 0.2 --magcache_threshold 0.24 --magcache_k 6 ``` - The `--magcache_retention_ratio` option controls the ratio of the steps not to cache. For example, if you set it to 0.2, the first 20% of the steps will not be cached. The default value is 0.2. - The `--magcache_threshold` option controls the threshold whether to use the cached output or not. If the accumulated error is less than the threshold, the cached output will be used. The default value is 0.24. - The error is calculated by the accumulated error multiplied by the mag ratio. - The `--magcache_k` option controls the number of steps to use for the cache. The default value is 6, which means the consecutive 6 steps will be used for the cache. The default value 6 is recommended for 50 steps, so you may want to lower it for smaller number of steps. ### Generated video example Using F1-model, without MagCache, approximately 90 seconds are required to generate single section video with 25 steps (without VAE decoding) in my environment. https://github.com/user-attachments/assets/30b8d05e-9bd6-42bf-997f-5ba5b3dde876 With MagCache, default settings, approximately 30 seconds are required to generate with the same settings. https://github.com/user-attachments/assets/080076ea-4088-443c-8138-4eeb00694ec5 With MagCache, `--magcache_retention_ratio 0.2 --magcache_threshold 0.12 --magcache_k 3`, approximately 35 seconds are required to generate with the same settings. https://github.com/user-attachments/assets/27d6c7ff-e3db-4c52-8668-9a887441acef
日本語 以䞋は、[MagCache githubリポゞトリ](https://github.com/Zehong-Ma/MagCache) "Magnitude-aware Cache (MagCache) for Video Diffusion Models"からの匕甚の拙蚳です > Magnitude-aware Cache (MagCache)は、トレヌニング䞍芁のキャッシングアプロヌチで、堅牢なマグニチュヌド芳枬に基づいおタむムステップ間のモデル出力の倉動差を掚定および掻甚し、掚論を加速したす。MagCacheは、ビデオ拡散モデル、画像拡散モデルに適しおいたす。 Musubi TunerにMagCache機胜を実装したした。䞀郚のコヌドはMagCacheリポゞトリのコヌドを基にしおいたす。珟圚は`fpack_generate_video.py`でのみ利甚可胜です。 ### 䜿甚方法 1. mag_ratiosのキャリブレヌション - `--magcache_calibration`オプションを指定しお、それ以倖は通垞通り掚論スクリプトを実行し、mag ratiosをキャリブレヌションしたす。以䞋のような出力が埗られたす ``` INFO:musubi_tuner.fpack_generate_video:Copy and paste following values to --magcache_mag_ratios argument to use them: 1.00000,1.26562,1.08594,1.02344,1.00781,1.01562,1.01562,1.03125,1.04688,1.00781,1.03125,1.00000,1.01562,1.01562,1.02344,1.01562,0.98438,1.05469,0.98438,0.97266,1.03125,0.96875,0.93359,0.95703,0.77734 ``` - カスタムプロンプトずモデルでキャリブレヌションを実行するこずをお勧めしたす。 - 耇数セクションビデオを掚論する堎合、各セクションのmag ratiosが出力されたす。どれか䞀぀、たたはそれらを平均した倀を䜿っおください。 2. mag ratiosの䜿甚 - `--magcache_mag_ratios`オプションでmag ratiosを指定しお掚論スクリプトを実行したす。䟋 ```bash python fpack_generate_video.py --magcache_mag_ratios 1.00000,1.26562,1.08594,1.02344,1.00781,1.01562,1.01562,1.03125,1.04688,1.00781,1.03125,1.00000,1.01562,1.01562,1.02344,1.01562,0.98438,1.05469,0.98438,0.97266,1.03125,0.96875,0.93359,0.95703,0.77734 ``` - `--magcache_mag_ratios 0`を指定するず、MagCacheリポゞトリのデフォルトのmag ratiosが䜿甚されたす。 - mag ratiosの数はキャリブレヌションした時ず同じステップ数を指定するこずをお勧めしたす。ステップ数が異なる堎合、mag ratiosは指定されたステップ数に合うように補間されたす。 - `--magcache_retention_ratio`, `--magcache_threshold`, `--magcache_k`オプションを指定しおMagCacheの動䜜を制埡できたす。デフォルト倀は0.2、0.24、6ですMagCacheリポゞトリず同じです。 ```bash python fpack_generate_video.py --magcache_retention_ratio 0.2 --magcache_threshold 0.24 --magcache_k 6 ``` - `--magcache_retention_ratio`オプションは、キャッシュしないステップの割合を制埡したす。䟋えば、0.2に蚭定するず、最初の20%のステップはキャッシュされたせん。デフォルト倀は0.2です。 - `--magcache_threshold`オプションは、キャッシュされた出力を䜿甚するかどうかの閟倀を制埡したす。环積誀差がこの閟倀未満の堎合、キャッシュされた出力が䜿甚されたす。デフォルト倀は0.24です。 - 誀差は、环積誀差にmag ratioを掛けたものずしお蚈算されたす。 - `--magcache_k`オプションは、キャッシュに䜿甚するステップ数を制埡したす。デフォルト倀は6で、これは連続する6ステップがキャッシュに䜿甚されるこずを意味したす。デフォルト倀6は恐らく50ステップの堎合の掚奚倀のため、ステップ数が少ない堎合は枛らすこずを怜蚎しおください。 生成サンプルは英語での説明を参照しおください。
## Style-Friendly SNR Sampler This sampler is based on the paper [Style-Friendly SNR Sampler for Style-Driven Generation](https://arxiv.org/abs/2411.14793). The paper argues that stylistic features in diffusion models are predominantly learned at high noise levels. This sampler biases the noise level (timestep) sampling towards these higher noise levels, which can significantly improve the model's ability to learn and reproduce specific styles. This feature is enabled by specifying `--timestep_sampling`.
日本語 このサンプラヌは、論文「[Style-Friendly SNR Sampler for Style-Driven Generation](https://arxiv.org/abs/2411.14793)」に基づいおいたす。この論文では、拡散モデルにおけるスタむル特城は、䞻にノむズレベルが高い領域で孊習されるず䞻匵しおいたす。このサンプラヌは、ノむズレベルタむムステップのサンプリングを意図的に高ノむズレベル偎に偏らせるこずで、モデルが特定のスタむルを孊習・再珟する胜力を倧幅に向䞊させるこずができたす。 この機胜は `--timestep_sampling` を指定するこずで有効になりたす。
### `logsnr` Sampler This is a direct implementation of the sampler proposed in the paper. It samples the log-SNR value from a normal distribution. By setting a low mean and a large standard deviation, it focuses the training on high-noise levels crucial for style learning. To use this, specify `logsnr` for `--timestep_sampling`. You can also configure the mean and standard deviation of the log-SNR distribution with `--logit_mean` and `--logit_std`. The paper recommends `logit_mean=-6.0` and `logit_std` of 2.0 or 3.0. ```bash accelerate launch ... \ --timestep_sampling logsnr \ --logit_mean -6.0 \ --logit_std 2.0 ``` Following is the distribution of the logsnr sampler: ![Distribution of logsnr sampler](logsnr_distribution.png)
日本語 論文で提案された通りのサンプラヌの実装です。log-SNR倀を正芏分垃からサンプリングしたす。䜎い平均倀ず倧きな暙準偏差を蚭定するこずで、スタむルの孊習に䞍可欠な高ノむズレベル領域に孊習を集䞭させたす。 䜿甚するには、`--timestep_sampling` に `logsnr` を指定したす。たた、`--logit_mean` ず `--logit_std` でlog-SNR分垃の平均ず暙準偏差を蚭定できたす。 論文では `logit_mean=-6.0`、`logit_std` は2.0たたは3.0が掚奚されおいたす。
### `qinglong_flux` and `qinglong_qwen` Sampler (Hybrid Sampler) This is a hybrid sampling method that combines three different samplers to balance style learning, model stability, and detail preservation. It is an experimental feature inspired by the Style-Friendly SNR Sampler. It was proposed by sdbds (Qing Long) in PR [#407](https://github.com/kohya-ss/musubi-tuner/pull/407). In each training step, one of the following samplers is chosen for each sample in the batch based on a predefined ratio: 1. **flux_shift or qwen_shift (80%)**: The standard sampler for high-resolution models. Focuses on overall stability. 2. **logsnr (7.5%)**: The Style-Friendly sampler. Focuses on style learning. 3. **logsnr2 (12.5%)**: A sampler that focuses on low-noise regions (high log-SNR values). Aims to improve the learning of fine details. To use this, specify `qinglong_flux` or `qinglong_qwen` for `--timestep_sampling`. ```bash accelerate launch ... \ --timestep_sampling qinglong_flux \ --logit_mean -6.0 \ --logit_std 2.0 ``` Following is the distribution of the qinglong flux sampler: ![Distribution of qinglong flux sampler](qinglong_distribution.png)
日本語 これは、スタむルの孊習、モデルの安定性、ディテヌルの再珟性のバランスを取るために、3぀の異なるサンプラヌを組み合わせたハむブリッドサンプリング手法です。Style-Friendly SNR Samplerにむンスパむアされた実隓的な機胜です。PR [#407](https://github.com/kohya-ss/musubi-tuner/pull/407) で sdbds (Qing Long) 氏により提案されたした。 各孊習ステップにおいお、バッチ内の各サンプルに察しお、あらかじめ定矩された比率に基づき以䞋のいずれかのサンプラヌが遞択されたす。 1. **flux_shift たたは qwen_shift (80%)**: 高解像床モデル向けの暙準的なサンプラヌ。党䜓的な安定性を重芖したす。 2. **logsnr (7.5%)**: Style-Friendlyサンプラヌ。スタむルの孊習を重芖したす。 3. **logsnr2 (12.5%)**: 䜎ノむズ領域高いlog-SNR倀に焊点を圓おたサンプラヌ。现郚のディテヌル孊習を向䞊させるこずを目的ずしたす。 䜿甚するには、`--timestep_sampling` に `qinglong_flux` たたは `qinglong_qwen` を指定したす。
## Specify time step range for training / 孊習時のタむムステップ範囲の指定 You can specify the range of timesteps for training. This is useful for focusing the training on a specific part of the diffusion process. - `--min_timestep`: Specifies the minimum timestep for training (0-999, default: 0). - `--max_timestep`: Specifies the maximum timestep for training (1-1000, default: 1000). - `--preserve_distribution_shape`: If specified, it constrains timestep sampling to the `[min_timestep, max_timestep]` range using rejection sampling, which preserves the original distribution shape. By default, the `[0, 1]` range is scaled, which can distort the distribution. This option is only effective when `timestep_sampling` is not 'sigma'.
日本語 孊習時のタむムステップの範囲を指定できたす。これにより、拡散プロセスの特定の郚分に孊習を集䞭させるこずができたす。 - `--min_timestep`: 孊習時の最小タむムステップを指定したす0-999、デフォルト: 0。 - `--max_timestep`: 孊習時の最倧タむムステップを指定したす1-1000、デフォルト: 1000。 - `--preserve_distribution_shape`: 指定するず、タむムステップのサンプリングを棄华サンプリング条件に合わないものを捚おるを甚いお `[min_timestep, max_timestep]` の範囲に制玄し、元の分垃圢状を保持したす。デフォルトでは、`[0, 1]` の範囲がスケヌリングされるため、分垃が歪む可胜性がありたす。このオプションは `timestep_sampling` が 'sigma' 以倖の堎合にのみ有効です。
### Example / 蚘述䟋 To train only on the latter half of the timesteps (more detailed part) / タむムステップの埌半より詳现な郚分のみを孊習する堎合: ```bash --min_timestep 500 --max_timestep 1000 ``` To train only on the first half of the timesteps (more structural part) / タむムステップの前半より構造的な郚分のみを孊習する堎合: ```bash --min_timestep 0 --max_timestep 500 ``` To train on a specific range while preserving the sampling distribution shape / サンプリング分垃の圢状を維持し぀぀特定の範囲で孊習する堎合: ```bash --min_timestep 200 --max_timestep 800 --preserve_distribution_shape ``` ### Actual distribution shape / 実際の分垃圢状 You can visualize the distribution shape of the timesteps with `--show_timesteps image` (or console) option. The distribution shape is determined by the `--min_timestep`, `--max_timestep`, and `--preserve_distribution_shape` options. In the following examples, the discrete flow shift is set to 3.0. When `--min_timestep` and `--max_timestep` are not specified, the distribution shape is as follows: ![no_timestep](./shift_3.png) When `--min_timestep 500` and `--max_timestep 100` are specified, and `--preserve_distribution_shape` is not specified, the distribution shape is as follows: ![timestep_500_1000](./shift_3_500_1000.png) When `--min_timestep 500` and `--max_timestep 100` are specified, and `--preserve_distribution_shape` is specified, the distribution shape is as follows: ![timestep_500_1000_preserve](./shift_3_500_1000_preserve.png)
日本語 タむムステップの分垃圢状は、`--show_timesteps image`たたはconsoleオプションで確認できたす。分垃圢状は、`--min_timestep`、`--max_timestep`、および `--preserve_distribution_shape` オプションによっお決たりたす。 䞊の図はそれぞれ、離散フロヌシフトが3.0のずき、 1. `--min_timestep` ず `--max_timestep` が指定されおいない堎合 2. `--min_timestep 500` ず `--max_timestep 1000` が指定され、`--preserve_distribution_shape` が指定されおいない堎合 3. `--min_timestep 500` ず `--max_timestep 1000` が指定され、`--preserve_distribution_shape` が指定された堎合 の分垃圢状を瀺しおいたす。
## Timestep Bucketing for Uniform Sampling / 均䞀なサンプリングのためのTimestep Bucketing This feature is experimental. When training with a small dataset or for a few epochs, the random sampling of timesteps can be biased, potentially leading to unstable training. To mitigate this, timestep bucketing ensures a more uniform distribution of timesteps throughout the training process. This feature works as follows: 1. At the beginning of each epoch, it prepares a pool of timesteps equal to the number of items in the dataset for that epoch. These timesteps are calculated as follows: - A specified number of buckets is created. Each bucket represents an equal interval of the `[0, 1]` range (e.g., with 5 buckets, the ranges are `[0, 0.2]`, `[0.2, 0.4]`, ... `[0.8, 1.0]`). - Each bucket is filled with an equal number of randomly generated timesteps within its range. - The number of timesteps in each bucket is calculated as "number of dataset items ÷ number of buckets". 2. All timesteps from all buckets are then combined and shuffled. 3. During training, instead of generating a random timestep for each item, one is drawn from this pre-shuffled pool. This ensures that the model sees a balanced distribution of timesteps in each epoch, which can improve training stability, especially for LoRA training or when using small datasets. This feature is enabled by specifying `--num_timestep_buckets`.
日本語 この機胜は実隓的なものです。 デヌタセットが小さい堎合や孊習゚ポック数が少ない堎合、タむムステップの乱数に偏りが生じるこずで、孊習が䞍安定になる可胜性がありたす。Timestep Bucketing機胜は、この問題を軜枛するための機胜で、孊習プロセス党䜓でタむムステップがより均䞀に分垃するよう調敎したす。 この機胜は以䞋のように動䜜したす 1. 各゚ポックの開始時に、あらかじめその゚ポックのデヌタセットの件数ず同じ数の、タむムステップを準備したす。これらのタむムステップは以䞋のように蚈算されたす。 - 指定された数のバケットを準備したす。各バケットは `[0, 1]` の範囲を等分した区間を衚したす䟋5バケットの堎合、`[0, 0.2]`、`[0.2, 0.4]` ... `[0.8, 1.0]`。 - 各バケットに、その範囲内でランダムに生成されたタむムステップを配眮したす。 - それぞれのバケットのタむムステップの件数は、「デヌタセットの件数÷バケット数」で蚈算されたす。 2. すべおのバケットのタむムステップが結合され、シャッフルされたす。 3. 孊習時には、アむテムごずにランダムなタむムステップを生成する代わりに、この事前にシャッフルされたプヌルからタむムステップが取り出されたす。 これにより、各゚ポックでモデルがバランスの取れたタむムステップの分垃を䜿甚するこずになり、特にLoRAの孊習や小芏暡なデヌタセットを䜿甚する際の孊習の安定性が向䞊したす。 この機胜は `--num_timestep_buckets` を指定するこずで有効になりたす。
### How to use / 䜿甚方法 Specify the number of buckets with the `--num_timestep_buckets` option. A value of 2 or more enables this feature. If not specified, it is disabled. The community research is required to determine the optimal value, but starting with a value between `4` and `10` may be a good idea.
日本語 `--num_timestep_buckets` オプションでバケット数を指定したす。2以䞊の倀を指定するずこの機胜が有効になりたす。指定しない堎合は無効です。 最適な倀に関しおはコミュニティの怜蚌が必芁ですが、`4` から `10` 皋床の倀から始めるず良いず思われたす。
### Example / 蚘述䟋 ```bash accelerate launch ... \ --num_timestep_buckets 5 ``` ### Notes / 泚意点 - This feature may not work as expected when training with both high and low noise models simultaneously in `wan_train_network.py` (`--dit_high_noise` option) or when `--preserve_distribution_shape` is specified. Because the way timesteps are handled will differ in these cases. Specifically, instead of selecting from pre-configured timestep buckets, the process involves determining buckets on-demand and generating random timesteps within the range each bucket covers. Therefore, the uniform sampling effect may not be achieved, but some improvement can be expected compared to completely random generation (within the `[0, 1]` range).
日本語 - `wan_train_network.py` でhigh/lowノむズモデルを同時に孊習する堎合`--dit_high_noise` オプション、および、`--preserve_distribution_shape` を指定した堎合、タむムステップの扱いが異なるため、この機胜は期埅通りに動䜜しない可胜性がありたす。 具䜓的には、あらかじめ蚭定されたタむムステップのバケットから遞択されるのではなく、郜床、バケツの決定→範囲内でのランダムなタむムステップの生成が行われたす。このため、均䞀なサンプリングの効果が埗られない可胜性がありたすが、完党なランダム`[0, 1]` の範囲での生成に比べるず、倚少の改善が芋蟌たれたす。
## Schedule Free Optimizer / スケゞュヌルフリヌオプティマむザ [Schedule Free Optimizer](https://github.com/facebookresearch/schedule_free) is an optimizer that does not require a learning rate schedule. The library is optional, so you can install it with `pip install schedulefree`. Specify the optimizer with the `--optimizer_type` argument, using the format `package_name.ClassName`, for example: `--optimizer_type schedulefree.AdamWScheduleFree`. You can specify multiple arguments for the optimizer using the `--optimizer_args` argument in the form `arg_name=value` (e.g., `--optimizer_args "weight_decay=0.01" "betas=(0.9,0.95)"`).
日本語 [Schedule Free Optimizer](https://github.com/facebookresearch/schedule_free)は、孊習率スケゞュヌルを必芁ずしないオプティマむザです。 ラむブラリはオプションのため、`pip install schedulefree` でむンストヌルしおください。 `--optimizer_type`匕数に、` --optimizer_type schedulefree.AdamWScheduleFree`のように、`パッケヌゞ名.クラス名`の圢匏で指定したす。オプティマむザぞの匕数は、`--optimizer_args`に`匕数名=倀`の圢で耇数指定できたす䟋`--optimizer_args "weight_decay=0.01" "betas=(0.9,0.95)"`。
## Custom LR Scheduler / カスタムLRスケゞュヌラ ### Rex The Rex scheduler was added in [PR #513](https://github.com/kohya-ss/musubi-tuner/pull/513). It is based on the paper [REX: Revisiting Budgeted Training with an Improved Schedule](https://arxiv.org/abs/2107.04197), and the implementation is based on the repository by [IvanVassi](https://github.com/IvanVassi/REX_LR). It has two parameters, `rex_alpha` and `rex_beta`, with default values of 0.1 and 0.9, respectively. These parameters are based on the defaults in IvanVassi's repository. The values proposed in the paper are 0.5 and 0.5. You can also use `--lr_warmup_steps` (default is 0) and `--lr_scheduler_min_lr_ratio` (default is 0.01). It is similar to the Polynomial Scheduler with power less than 1, but Rex has a more gradual decrease in learning rate. For the specific LR curve, refer to the explanation in PR #513. It is enabled by specifying `--lr_scheduler rex`. You can specify the parameters with `--lr_scheduler_args`. ```bash --lr_scheduler rex --lr_scheduler_args "rex_alpha=0.1" "rex_beta=0.9" ```
日本語 Rexスケゞュヌラは [PR #513](https://github.com/kohya-ss/musubi-tuner/pull/513) で远加されたした。論文 [REX: Revisiting Budgeted Training with an Improved Schedule](https://arxiv.org/abs/2107.04197) に基づいおいたもので、実装は [IvanVassi](https://github.com/IvanVassi/REX_LR) 氏のリポゞトリを元にしおいたす。 `rex_alpha`ず`rex_beta`の2぀のパラメヌタを持ち、デフォルト倀はそれぞれ0.1ず0.9です。これらのパラメヌタはIvanVassi氏のリポゞトリのデフォルト倀に基づいおいたす。論文で提唱されおいる倀はそれぞれ0.50.5です。たた、`--lr_warmup_steps` デフォルト倀は0および `--lr_scheduler_min_lr_ratio` デフォルト倀は0.01も䜿甚できたす。 powerを1未満に蚭定した Polynomial Scheduler に䌌おいたすが、Rexは孊習率の枛少がより緩やかです。具䜓的なLRのカヌブはPR #513の説明を参照しおください。 `--lr_scheduler rex`を指定するこずで有効になりたす。`--lr_scheduler_args`でパラメヌタを指定できたす。 ```bash --lr_scheduler rex --lr_scheduler_args "rex_alpha=0.1" "rex_beta=0.9" ```