SuperCS's picture
Add files using upload-large-folder tool
2336cc9 verified

📝 Click on the language section to expand / 蚀語をクリックしお展開

Advanced configuration / 高床な蚭定

Table of contents / 目次

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. / コマンドラむンで指定する堎合は以䞋のように蚘述したす。

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. / 蚭定ファむルで指定する堎合は以䞋のように蚘述したす。

network_args = ["key1=value1", "key2=value2", ...]

If you specify "verbose=True", detailed information of LoRA will be displayed. / "verbose=True"を指定するずLoRAの詳现な情報が衚瀺されたす。

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

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 / 蚘述䟋

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のモゞュヌルのみを察象ずする堎合:

--network_args "exclude_patterns=[r'.*single_blocks.*']"

Only the modules of single blocks from the 10th / single blocksの10番目以降のLinearモゞュヌルのみを察象ずする堎合:

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

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でログを確認するには、別のコマンドプロンプトを開き、仮想環境を有効にしおから、䜜業フォルダで以䞋のように入力したす。

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 is available to quantize the weights of the model to FP8 (E4M3) format with appropriate scaling. This reduces the VRAM usage while maintaining precision. Important weights are kept in FP16/BF16/FP32 format.

The model weights must be in fp16 or bf16. Weights that have been pre-converted to float8_e4m3 cannot be used.

Wan2.1 inference and training are supported.

Specify the --fp8_scaled option in addition to the --fp8 option during inference.

Specify the --fp8_scaled option in addition to the --fp8_base option during training.

Acknowledgments: This feature is based on the implementation of HunyuanVideo. The selection of high-precision modules is based on the implementation of diffusion-pipe. I would like to thank these repositories.

日本語 重みを単玔にFP8ぞcastするのではなく、適切なスケヌリングでFP8圢匏に量子化するこずで、粟床を維持し぀぀VRAM䜿甚量を削枛したす。たた、重芁な重みはFP16/BF16/FP32圢匏で保持したす。

モデルの重みは、fp16たたはbf16が必芁です。あらかじめfloat8_e4m3に倉換された重みは䜿甚できたせん。

Wan2.1の掚論、孊習のみ察応しおいたす。

掚論時は--fp8オプションに加えお --fp8_scaledオプションを指定しおください。

孊習時は--fp8_baseオプションに加えお --fp8_scaledオプションを指定しおください。

謝蟞この機胜は、HunyuanVideoの実装を参考にしたした。たた、高粟床モゞュヌルの遞択においおはdiffusion-pipeの実装を参考にしたした。これらのリポゞトリに感謝したす。

Key features and implementation details / 䞻な特城ず実装の詳现

  • Implements FP8 (E4M3) weight quantization for Linear layers
  • 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
  • Maintains computational precision by dequantizing to original precision (FP16/BF16/FP32) during forward pass
  • Preserves important weights in FP16/BF16/FP32 format

The implementation:

  1. Quantizes weights to FP8 format with appropriate scaling
  2. Replaces weights by FP8 quantized weights and stores scale factors in model state dict
  3. Applies monkey patching to Linear layers for transparent dequantization during computation
日本語
  • Linear局のFP8E4M3重み量子化を実装
  • 8ビットの重みを䜿甚するこずでVRAM䜿甚量を削枛既存の--fp8 --fp8_base オプションに比べお埮増
  • 単玔なFP8ぞのcastではなく、適切な倀でスケヌルしお重みをFP8圢匏に量子化
  • forward時に元の粟床FP16/BF16/FP32に逆量子化しお蚈算粟床を維持
  • 粟床が重芁な重みはFP16/BF16/FP32のたた保持

実装:

  1. 粟床を維持できる適切な倍率で重みをFP8圢匏に量子化
  2. 重みをFP8量子化重みに眮き換え、倍率をモデルのstate dictに保存
  3. Linear局にmonkey patchingするこずでモデルを倉曎せずに逆量子化

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

python src/musubi_tuner/hv_train_network.py --dynamo_backend INDUCTOR --dynamo_mode default

For more aggressive optimization:

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 で远加されたした。

--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
    可倉入力圢状を持぀モデルのための動的圢状凊理を有効にするフラグ

䜿甚䟋

python src/musubi_tuner/hv_train_network.py --dynamo_backend INDUCTOR --dynamo_mode default

より積極的な最適化の堎合

python src/musubi_tuner/hv_train_network.py --dynamo_backend INDUCTOR --dynamo_mode max-autotune --dynamo_fullgraph

泚意最適なオプションの組み合わせは、特定のモデルずハヌドりェアに䟝存する堎合がありたす。最適な構成を芋぀けるために実隓が必芁かもしれたせん。

LoRA Post-Hoc EMA merging / LoRAのPost-Hoc EMAマヌゞ

The LoRA Post-Hoc EMA (Exponential Moving Average) merging is a technique to combine multiple LoRA checkpoint files into a single, potentially more stable model. This method applies exponential moving average across multiple checkpoints sorted by modification time, with configurable decay rates.

The Post-Hoc EMA method works by:

  1. Sorting checkpoint files by modification time (oldest to newest)
  2. Using the oldest checkpoint as the base
  3. Iteratively merging subsequent checkpoints with a decay rate (beta)
  4. Optionally using linear interpolation between two beta values across the merge process

Pseudo-code for merging multiple checkpoints with beta=0.95 would look like this:

beta = 0.95
checkpoints = [checkpoint1, checkpoint2, checkpoint3]  # List of checkpoints
merged_weights = checkpoints[0]  # Use the first checkpoint as the base
for checkpoint in checkpoints[1:]:
    merged_weights = beta * merged_weights + (1 - beta) * checkpoint

Key features:

  • Temporal ordering: Automatically sorts files by modification time
  • Configurable decay rates: Supports single beta value or linear interpolation between two beta values
  • Metadata preservation: Maintains and updates metadata from the last checkpoint
  • Hash updating: Recalculates model hashes for the merged weights
  • Dtype preservation: Maintains original data types of tensors

Usage

The LoRA Post-Hoc EMA merging is available as a standalone script:

python src/musubi_tuner/lora_post_hoc_ema.py checkpoint1.safetensors checkpoint2.safetensors checkpoint3.safetensors --output_file merged_lora.safetensors --beta 0.95

Command line options:

path [path ...]
    List of paths to the LoRA weight files to merge

--beta BETA
    Decay rate for merging weights (default: 0.95)
    Higher values (closer to 1.0) give more weight to the accumulated average
    Lower values give more weight to the current checkpoint

--beta2 BETA2
    Second decay rate for linear interpolation (optional)
    If specified, the decay rate will linearly interpolate from beta to beta2
    across the merging process

--sigma_rel SIGMA_REL
    Relative sigma for Power Function EMA (optional, mutually exclusive with beta/beta2)
    This resolves the issue where the first checkpoint has a disproportionately large influence when beta is specified.
    If specified, beta is calculated using the Power Function EMA method from the paper:
    https://arxiv.org/pdf/2312.02696. This overrides beta and beta2.

--output_file OUTPUT_FILE
    Output file path for the merged weights (required)

--no_sort
    Disable sorting of checkpoint files (merge in specified order)

Examples:

Basic usage with constant decay rate:

python src/musubi_tuner/lora_post_hoc_ema.py \
    lora_epoch_001.safetensors \
    lora_epoch_002.safetensors \
    lora_epoch_003.safetensors \
    --output_file lora_ema_merged.safetensors \
    --beta 0.95

Using linear interpolation between two decay rates:

python src/musubi_tuner/lora_post_hoc_ema.py \
    lora_epoch_001.safetensors \
    lora_epoch_002.safetensors \
    lora_epoch_003.safetensors \
    --output_file lora_ema_interpolated.safetensors \
    --beta 0.90 \
    --beta2 0.95

Using Power Function EMA with sigma_rel:

python src/musubi_tuner/lora_post_hoc_ema.py \
    lora_epoch_001.safetensors \
    lora_epoch_002.safetensors \
    lora_epoch_003.safetensors \
    --output_file lora_power_ema_merged.safetensors \
    --sigma_rel 0.2

betas for different σ-rel values:

beta-sigma_rel-graph

Recommended settings example (after training for 30 epochs, using --beta)

If you're unsure which settings to try, start with the following "General Recommended Settings".

1. General Recommended Settings (start with these combinations)

  • Target Epochs: 15-30 (the latter half of training)
  • beta: 0.9 (a balanced value)

2. If training converged early

  • Situation: Loss dropped early and stabilized afterwards.
  • Target Epochs: 10-30 (from the epoch where loss stabilized to the end)
  • beta: 0.95 (wider range, smoother)

3. If you want to avoid overfitting

  • Situation: In the latter part of training, generated results are too similar to training data.
  • Target Epochs: 15-25 (focus on the peak performance range)
  • beta: 0.8 (more emphasis on the latter part of the range while maintaining diversity)

Note: The optimal values may vary depending on the model and dataset. It's recommended to experiment with multiple beta values (e.g., 0.8, 0.9, 0.95) and compare the generated results.

Recommended Settings Example (30 epochs training, using --sigma_rel)

When using --sigma_rel, the beta decay schedule is determined by the Power Function EMA method. Here are some starting points:

1. General Recommended Settings

  • Target Epochs: All epochs (from the first to the last).
  • sigma_rel: 0.2 (a general starting point).

2. If training converged early

  • Situation: Loss dropped early and stabilized afterwards.
  • Target Epochs: All epochs.
  • sigma_rel: 0.25 (gives more weight to earlier checkpoints, suitable for early convergence).

3. If you want to avoid overfitting

  • Situation: In the latter part of training, generated results are too similar to training data.
  • Target Epochs: From the first epoch, omitting the last few potentially overfitted epochs.
  • sigma_rel: 0.15 (gives more weight to later (but not the very last) checkpoints, helping to mitigate overfitting from the final stages).

Note: The optimal sigma_rel value can depend on the dataset, model, and training duration. Experimentation is encouraged. Values typically range from 0.1 to 0.5. A graph showing the relationship between sigma_rel and the calculated beta values over epochs will be provided later to help understand its behavior.

Notes:

  • Files are automatically sorted by modification time, so the order in the command line doesn't matter
  • The --sigma_rel option is mutually exclusive with --beta and --beta2. If --sigma_rel is provided, it will determine the beta values, and any provided --beta or --beta2 will be ignored.
  • All checkpoint files to be merged should be from the same training run, saved per epoch or step
    • Merging is possible if shapes match, but may not work correctly as Post Hoc EMA
  • All checkpoint files must have the same alpha value
  • The merged model will have updated hash values in its metadata
  • The metadata of the merged model will be taken from the last checkpoint, with only the hash value recalculated
  • Non-float tensors (long, int, bool, etc.) are not merged and will use the first checkpoint's values
  • Processing is done in float32 precision to maintain numerical stability during merging. The original data types are preserved when saving
日本語

LoRA Post-Hoc EMA指数移動平均マヌゞは、耇数のLoRAチェックポむントファむルを単䞀の、より安定したモデルに結合する手法です。スクリプトでは、修正時刻で゜ヌト叀い順された耇数のチェックポむントに察しお指定された枛衰率で指数移動平均を適甚したす。枛衰率は指定可胜です。

Post-Hoc EMA方法の動䜜

  1. チェックポむントファむルを修正時刻順叀いものから新しいものぞに゜ヌト
  2. 最叀のチェックポむントをベヌスずしお䜿甚
  3. 枛衰率betaを䜿っお埌続のチェックポむントを反埩的にマヌゞ
  4. オプションで、マヌゞプロセス党䜓で2぀のベヌタ倀間の線圢補間を䜿甚

疑䌌コヌドによるむメヌゞ耇数のチェックポむントをbeta=0.95でマヌゞする堎合、次のように蚈算されたす。

beta = 0.95
checkpoints = [checkpoint1, checkpoint2, checkpoint3]  # チェックポむントのリスト
merged_weights = checkpoints[0]  # 最初のチェックポむントをベヌスずしお䜿甚
for checkpoint in checkpoints[1:]:
    merged_weights = beta * merged_weights + (1 - beta) * checkpoint

䞻な特城

  • 時系列順序付け: ファむルを修正時刻で自動的に゜ヌト
  • 蚭定可胜な枛衰率: 単䞀のベヌタ倀たたは2぀のベヌタ倀間の線圢補間をサポヌト
  • メタデヌタ保持: 最埌のチェックポむントからメタデヌタを維持・曎新
  • ハッシュ曎新: マヌゞされた重みのモデルハッシュを再蚈算
  • デヌタ型保持: テン゜ルの元のデヌタ型を維持

䜿甚法

LoRA Post-Hoc EMAマヌゞは独立したスクリプトずしお提䟛されおいたす

python src/musubi_tuner/lora_post_hoc_ema.py checkpoint1.safetensors checkpoint2.safetensors checkpoint3.safetensors --output_file merged_lora.safetensors --beta 0.95

コマンドラむンオプション

path [path ...]
    マヌゞするLoRA重みファむルのパスのリスト

--beta BETA
    重みマヌゞのための枛衰率デフォルト0.95
    高い倀1.0に近いは环積平均により倧きな重みを䞎える叀いチェックポむントを重芖
    䜎い倀は珟圚のチェックポむントにより倧きな重みを䞎える

--beta2 BETA2
    線圢補間のための第2枛衰率オプション
    指定された堎合、枛衰率はマヌゞプロセス党䜓でbetaからbeta2ぞ線圢補間される

--sigma_rel SIGMA_REL
    Power Function EMAのための盞察シグマオプション、beta/beta2ず同時に指定できたせん
    betaを指定した堎合の、最初のチェックポむントが盞察的に倧きな圱響を持぀欠点を解決したす
    指定された堎合、betaは次の論文に基づいおPower Function EMA法で蚈算されたす
    https://arxiv.org/pdf/2312.02696. これによりbetaずbeta2が䞊曞きされたす。

--output_file OUTPUT_FILE
    マヌゞされた重みの出力ファむルパス必須

--no_sort
    チェックポむントファむルの゜ヌトを無効にする指定した順序でマヌゞ

䟋

定数枛衰率での基本的な䜿甚法

python src/musubi_tuner/lora_post_hoc_ema.py \
    lora_epoch_001.safetensors \
    lora_epoch_002.safetensors \
    lora_epoch_003.safetensors \
    --output_file lora_ema_merged.safetensors \
    --beta 0.95

2぀の枛衰率間の線圢補間を䜿甚

python src/musubi_tuner/lora_post_hoc_ema.py \
    lora_epoch_001.safetensors \
    lora_epoch_002.safetensors \
    lora_epoch_003.safetensors \
    --output_file lora_ema_interpolated.safetensors \
    --beta 0.90 \
    --beta2 0.95

シグマ_relを䜿甚したPower Function EMA

python src/musubi_tuner/lora_post_hoc_ema.py \
    lora_epoch_001.safetensors \
    lora_epoch_002.safetensors \
    lora_epoch_003.safetensors \
    --output_file lora_power_ema_merged.safetensors \
    --sigma_rel 0.2

掚奚蚭定の䟋 (30゚ポック孊習し、 --betaを䜿甚する堎合)

どの蚭定から詊せば良いか分からない堎合は、たず以䞋の「䞀般的な掚奚蚭定」から始めおみおください。

1. 䞀般的な掚奚蚭定 (たず詊すべき組み合わせ)

  • 察象゚ポック: 15-30 (孊習の埌半半分)
  • beta: 0.9 (バランスの取れた倀)

2. 早期に孊習が収束した堎合

  • 状況: lossが早い段階で䞋がり、その埌は安定しおいる。
  • 察象゚ポック: 10-30 (lossが安定し始めた゚ポックから最埌たで)
  • beta: 0.95 (察象範囲が広いので、より滑らかにする)

3. 過孊習を避けたい堎合

  • 状況: 孊習の最埌の方で、生成結果が孊習デヌタに䌌すぎおいる。
  • 察象゚ポック: 15-25 (性胜のピヌクず思われる範囲に絞る)
  • beta: 0.8 (範囲の終盀を重芖し぀぀、倚様性を残す)

ヒント: 最適な倀はモデルやデヌタセットによっお異なりたす。耇数のbeta䟋: 0.8, 0.9, 0.95を詊しお、生成結果を比范するこずをお勧めしたす。

掚奚蚭定の䟋 (30゚ポック孊習し、 --sigma_relを䜿甚する堎合)

--sigma_rel を䜿甚する堎合、betaの枛衰スケゞュヌルはPower Function EMA法によっお決定されたす。以䞋はいく぀かの開始点です。

1. 䞀般的な掚奚蚭定

  • 察象゚ポック: 党おの゚ポック最初から最埌たで
  • sigma_rel: 0.2 䞀般的な開始点

2. 早期に孊習が収束した堎合

  • 状況: lossが早い段階で䞋がり、その埌は安定しおいる。
  • 察象゚ポック: 党おの゚ポック
  • sigma_rel: 0.25 初期のチェックポむントに重きを眮くため、早期収束に適しおいたす

3. 過孊習を避けたい堎合

  • 状況: 孊習の最埌の方で、生成結果が孊習デヌタに䌌すぎおいる。
  • 察象゚ポック: 最初の゚ポックから、過孊習の可胜性がある最埌の数゚ポックを陀倖
  • sigma_rel: 0.15 終盀ただし最埌の最埌ではないのチェックポむントに重きを眮き、最終段階での過孊習を軜枛するのに圹立ちたす

ヒント: 最適な sigma_rel の倀は、デヌタセット、モデル、孊習期間によっお異なる堎合がありたす。実隓を掚奚したす。倀は通垞0.1から0.5の範囲です。sigma_rel ず゚ポックごずの蚈算された beta 倀の関係を瀺すグラフは、その挙動を理解するのに圹立぀よう埌ほど提䟛する予定です。

泚意点

  • ファむルは修正時刻で自動的に゜ヌトされるため、コマンドラむンでの順序は関係ありたせん
  • --sigma_relオプションは--betaおよび--beta2ず盞互に排他的です。--sigma_relが指定された堎合、それがベヌタ倀を決定し、指定された--betaたたは--beta2は無芖されたす。
  • マヌゞする党おのチェックポむントファむルは、ひず぀の孊習で、゚ポックごず、たたはステップごずに保存されたモデルである必芁がありたす
    • 圢状が䞀臎しおいればマヌゞはできたすが、Post Hoc EMAずしおは正しく動䜜したせん
  • alpha倀はすべおのチェックポむントで同じである必芁がありたす
  • マヌゞされたモデルのメタデヌタは、最埌のチェックポむントのものが利甚されたす。ハッシュ倀のみが再蚈算されたす
  • 浮動小数点以倖の、long、int、boolなどのテン゜ルはマヌゞされたせん最初のチェックポむントのものが䜿甚されたす
  • マヌゞ䞭の数倀安定性を維持するためにfloat32粟床で蚈算されたす。保存時は元のデヌタ型が維持されたす

MagCache

The following is quoted from the MagCache github repository "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:
    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).
    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リポゞトリ "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を指定しお掚論スクリプトを実行したす。䟋
     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リポゞトリず同じです。
     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ステップの堎合の掚奚倀のため、ステップ数が少ない堎合は枛らすこずを怜蚎しおください。

生成サンプルは英語での説明を参照しおください。