📝 Click on the language section to expand / 言語をクリックして展開
- How to specify
network_args - LoRA+
- Select the target modules of LoRA
- Save and view logs in TensorBoard format
- Save and view logs in wandb
- FP8 weight optimization for models
- PyTorch Dynamo optimization for model training
- LoRA Post-Hoc EMA merging
- MagCache
- Style-Friendly SNR Sampler
- Specify time step range for training
- Timestep Bucketing for Uniform Sampling
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`の形式で引数を指定します。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+ 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を指定します。
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" ...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).*が指定されています。)
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.*']"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/ へアクセスすると表示されます。
--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でプロジェクト名を指定してください。
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の実装を参考にしました。これらのリポジトリに感謝します。
- 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_baseoptions) - 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:
- Quantizes weights to FP8 format with appropriate scaling
- Replaces weights by FP8 quantized weights and stores scale factors in model state dict
- 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のまま保持
実装:
- 精度を維持できる適切な倍率で重みをFP8形式に量子化
- 重みをFP8量子化重みに置き換え、倍率をモデルのstate dictに保存
- Linear層にmonkey patchingすることでモデルを変更せずに逆量子化
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.
--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
python src/musubi_tuner/hv_train_network.py --dynamo_backend INDUCTOR --dynamo_mode defaultFor more aggressive optimization:
python src/musubi_tuner/hv_train_network.py --dynamo_backend INDUCTOR --dynamo_mode max-autotune --dynamo_fullgraphNote: 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注意:最適なオプションの組み合わせは、特定のモデルとハードウェアに依存する場合があります。最適な構成を見つけるために実験が必要かもしれません。
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:
- Sorting checkpoint files by modification time (oldest to newest)
- Using the oldest checkpoint as the base
- Iteratively merging subsequent checkpoints with a decay rate (beta)
- 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
- 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
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.95path [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)
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.95Using 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.95Using 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.2If you're unsure which settings to try, start with the following "General Recommended Settings".
- Target Epochs:
15-30(the latter half of training) - beta:
0.9(a balanced value)
- 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)
- 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.
When using --sigma_rel, the beta decay schedule is determined by the Power Function EMA method. Here are some starting points:
- Target Epochs: All epochs (from the first to the last).
- sigma_rel:
0.2(a general starting point).
- 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).
- 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.
- Files are automatically sorted by modification time, so the order in the command line doesn't matter
- The
--sigma_reloption is mutually exclusive with--betaand--beta2. If--sigma_relis provided, it will determine the beta values, and any provided--betaor--beta2will 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方法の動作:
- チェックポイントファイルを修正時刻順(古いものから新しいものへ)にソート
- 最古のチェックポイントをベースとして使用
- 減衰率(beta)を使って後続のチェックポイントを反復的にマージ
- オプションで、マージプロセス全体で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.95path [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.952つの減衰率間の線形補間を使用:
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どの設定から試せば良いか分からない場合は、まず以下の「一般的な推奨設定」から始めてみてください。
- 対象エポック:
15-30(学習の後半半分) - beta:
0.9(バランスの取れた値)
- 状況: lossが早い段階で下がり、その後は安定している。
- 対象エポック:
10-30(lossが安定し始めたエポックから最後まで) - beta:
0.95(対象範囲が広いので、より滑らかにする)
- 状況: 学習の最後の方で、生成結果が学習データに似すぎている。
- 対象エポック:
15-25(性能のピークと思われる範囲に絞る) - beta:
0.8(範囲の終盤を重視しつつ、多様性を残す)
ヒント: 最適な値はモデルやデータセットによって異なります。複数のbeta(例: 0.8, 0.9, 0.95)を試して、生成結果を比較することをお勧めします。
--sigma_rel を使用する場合、betaの減衰スケジュールはPower Function EMA法によって決定されます。以下はいくつかの開始点です。
- 対象エポック: 全てのエポック(最初から最後まで)
- sigma_rel:
0.2(一般的な開始点)
- 状況: lossが早い段階で下がり、その後は安定している。
- 対象エポック: 全てのエポック
- sigma_rel:
0.25(初期のチェックポイントに重きを置くため、早期収束に適しています)
- 状況: 学習の最後の方で、生成結果が学習データに似すぎている。
- 対象エポック: 最初のエポックから、過学習の可能性がある最後の数エポックを除外
- 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精度で計算されます。保存時は元のデータ型が維持されます
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.
-
Calibrate the mag ratios
- Run the inference script as normal, but with the
--magcache_calibrationoption 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.
- Run the inference script as normal, but with the
-
Use the mag ratios
- Run the inference script with the
--magcache_mag_ratiosoption 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 0to 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_koptions 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_ratiooption 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_thresholdoption 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_koption 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.
- Run the inference script with the
Using F1-model, without MagCache, approximately 90 seconds are required to generate single section video with 25 steps (without VAE decoding) in my environment.
without_magcache.mp4
With MagCache, default settings, approximately 30 seconds are required to generate with the same settings.
magcache_default.mp4
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.
magcache_thres_012_k3.mp4
日本語
以下は、MagCache githubリポジトリ "Magnitude-aware Cache (MagCache) for Video Diffusion Models"からの引用の拙訳です:
Magnitude-aware Cache (MagCache)は、トレーニング不要のキャッシングアプローチで、堅牢なマグニチュード観測に基づいてタイムステップ間のモデル出力の変動差を推定および活用し、推論を加速します。MagCacheは、ビデオ拡散モデル、画像拡散モデルに適しています。
Musubi TunerにMagCache機能を実装しました。一部のコードはMagCacheリポジトリのコードを基にしています。現在はfpack_generate_video.pyでのみ利用可能です。
-
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が出力されます。どれか一つ、またはそれらを平均した値を使ってください。
-
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ステップの場合の推奨値のため、ステップ数が少ない場合は減らすことを検討してください。
生成サンプルは英語での説明を参照してください。
This sampler is based on the paper Style-Friendly SNR Sampler for Style-Driven Generation. 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」に基づいています。この論文では、拡散モデルにおけるスタイル特徴は、主にノイズレベルが高い領域で学習されると主張しています。このサンプラーは、ノイズレベル(タイムステップ)のサンプリングを意図的に高ノイズレベル側に偏らせることで、モデルが特定のスタイルを学習・再現する能力を大幅に向上させることができます。
この機能は --timestep_sampling を指定することで有効になります。
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.
accelerate launch ... \
--timestep_sampling logsnr \
--logit_mean -6.0 \
--logit_std 2.0Following is the distribution of the logsnr sampler:
日本語
論文で提案された通りのサンプラーの実装です。log-SNR値を正規分布からサンプリングします。低い平均値と大きな標準偏差を設定することで、スタイルの学習に不可欠な高ノイズレベル領域に学習を集中させます。
使用するには、--timestep_sampling に logsnr を指定します。また、--logit_mean と --logit_std でlog-SNR分布の平均と標準偏差を設定できます。
論文では logit_mean=-6.0、logit_std は2.0または3.0が推奨されています。
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.
In each training step, one of the following samplers is chosen for each sample in the batch based on a predefined ratio:
- flux_shift or qwen_shift (80%): The standard sampler for high-resolution models. Focuses on overall stability.
- logsnr (7.5%): The Style-Friendly sampler. Focuses on style learning.
- 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.
accelerate launch ... \
--timestep_sampling qinglong_flux \
--logit_mean -6.0 \
--logit_std 2.0Following is the distribution of the qinglong flux sampler:
日本語
これは、スタイルの学習、モデルの安定性、ディテールの再現性のバランスを取るために、3つの異なるサンプラーを組み合わせたハイブリッドサンプリング手法です。Style-Friendly SNR Samplerにインスパイアされた実験的な機能です。PR #407 で sdbds (Qing Long) 氏により提案されました。
各学習ステップにおいて、バッチ内の各サンプルに対して、あらかじめ定義された比率に基づき以下のいずれかのサンプラーが選択されます。
- flux_shift または qwen_shift (80%): 高解像度モデル向けの標準的なサンプラー。全体的な安定性を重視します。
- logsnr (7.5%): Style-Friendlyサンプラー。スタイルの学習を重視します。
- logsnr2 (12.5%): 低ノイズ領域(高いlog-SNR値)に焦点を当てたサンプラー。細部のディテール学習を向上させることを目的とします。
使用するには、--timestep_sampling に qinglong_flux または qinglong_qwen を指定します。
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 whentimestep_samplingis not 'sigma'.
日本語
学習時のタイムステップの範囲を指定できます。これにより、拡散プロセスの特定の部分に学習を集中させることができます。
--min_timestep: 学習時の最小タイムステップを指定します(0-999、デフォルト: 0)。--max_timestep: 学習時の最大タイムステップを指定します(1-1000、デフォルト: 1000)。--preserve_distribution_shape: 指定すると、タイムステップのサンプリングを棄却サンプリング(条件に合わないものを捨てる)を用いて[min_timestep, max_timestep]の範囲に制約し、元の分布形状を保持します。デフォルトでは、[0, 1]の範囲がスケーリングされるため、分布が歪む可能性があります。このオプションはtimestep_samplingが 'sigma' 以外の場合にのみ有効です。
To train only on the latter half of the timesteps (more detailed part) / タイムステップの後半(より詳細な部分)のみを学習する場合:
--min_timestep 500 --max_timestep 1000To train only on the first half of the timesteps (more structural part) / タイムステップの前半(より構造的な部分)のみを学習する場合:
--min_timestep 0 --max_timestep 500To train on a specific range while preserving the sampling distribution shape / サンプリング分布の形状を維持しつつ特定の範囲で学習する場合:
--min_timestep 200 --max_timestep 800 --preserve_distribution_shapeYou 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:
When --min_timestep 500 and --max_timestep 100 are specified, and --preserve_distribution_shape is not specified, the distribution shape is as follows:
When --min_timestep 500 and --max_timestep 100 are specified, and --preserve_distribution_shape is specified, the distribution shape is as follows:
日本語
タイムステップの分布形状は、--show_timesteps image(またはconsole)オプションで確認できます。分布形状は、--min_timestep、--max_timestep、および --preserve_distribution_shape オプションによって決まります。
上の図はそれぞれ、離散フローシフトが3.0のとき、
--min_timestepと--max_timestepが指定されていない場合--min_timestep 500と--max_timestep 1000が指定され、--preserve_distribution_shapeが指定されていない場合--min_timestep 500と--max_timestep 1000が指定され、--preserve_distribution_shapeが指定された場合
の分布形状を示しています。
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:
-
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".
- A specified number of buckets is created. Each bucket represents an equal interval of the
-
All timesteps from all buckets are then combined and shuffled.
-
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機能は、この問題を軽減するための機能で、学習プロセス全体でタイムステップがより均一に分布するよう調整します。
この機能は以下のように動作します:
-
各エポックの開始時に、あらかじめそのエポックのデータセットの件数と同じ数の、タイムステップを準備します。これらのタイムステップは以下のように計算されます。
- 指定された数のバケットを準備します。各バケットは
[0, 1]の範囲を等分した区間を表します(例:5バケットの場合、[0, 0.2]、[0.2, 0.4]...[0.8, 1.0])。 - 各バケットに、その範囲内でランダムに生成されたタイムステップを配置します。
- それぞれのバケットのタイムステップの件数は、「データセットの件数÷バケット数」で計算されます。
- 指定された数のバケットを準備します。各バケットは
-
すべてのバケットのタイムステップが結合され、シャッフルされます。
-
学習時には、アイテムごとにランダムなタイムステップを生成する代わりに、この事前にシャッフルされたプールからタイムステップが取り出されます。
これにより、各エポックでモデルがバランスの取れたタイムステップの分布を使用することになり、特にLoRAの学習や小規模なデータセットを使用する際の学習の安定性が向上します。
この機能は --num_timestep_buckets を指定することで有効になります。
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 程度の値から始めると良いと思われます。
accelerate launch ... \
--num_timestep_buckets 5-
This feature may not work as expected when training with both high and low noise models simultaneously in
wan_train_network.py(--dit_high_noiseoption) or when--preserve_distribution_shapeis 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]の範囲での生成)に比べると、多少の改善が見込まれます。





