diff --git a/.gitattributes b/.gitattributes index bed0738c7eeb449bca98b5d2f33c89a1ee56349a..48765a7b8dd54db45583fe7c60aa9a728377be57 100644 --- a/.gitattributes +++ b/.gitattributes @@ -58,3 +58,19 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text # Video files - compressed *.mp4 filter=lfs diff=lfs merge=lfs -text *.webm filter=lfs diff=lfs merge=lfs -text +VRGDG_Musubi-tuner/models/gemma-3-12b-it/tokenizer.json filter=lfs diff=lfs merge=lfs -text +VRGDG_Musubi-tuner/src/musubi_tuner/__pycache__/hv_train_network.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +VRGDG_Musubi-tuner/src/musubi_tuner/__pycache__/ltx2_remote_stage.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +VRGDG_Musubi-tuner/src/musubi_tuner/__pycache__/ltx2_sampling.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +VRGDG_Musubi-tuner/src/musubi_tuner/__pycache__/ltx2_train_network.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +VRGDG_Musubi-tuner/src/musubi_tuner/dataset/__pycache__/image_video_dataset.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +VRGDG_Musubi-tuner/venv/bin/python filter=lfs diff=lfs merge=lfs -text +VRGDG_Musubi-tuner/venv/bin/python3 filter=lfs diff=lfs merge=lfs -text +VRGDG_Musubi-tuner/venv/bin/python3.12 filter=lfs diff=lfs merge=lfs -text +VRGDG_Musubi-tuner/venv/lib/python3.12/site-packages/pip/_vendor/__pycache__/typing_extensions.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +VRGDG_Musubi-tuner/venv/lib/python3.12/site-packages/pip/_vendor/chardet/__pycache__/langrussianmodel.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +VRGDG_Musubi-tuner/venv/lib/python3.12/site-packages/pip/_vendor/idna/__pycache__/uts46data.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +VRGDG_Musubi-tuner/venv/lib/python3.12/site-packages/pip/_vendor/pkg_resources/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +VRGDG_Musubi-tuner/venv/lib/python3.12/site-packages/pip/_vendor/pyparsing/__pycache__/core.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +VRGDG_Musubi-tuner/venv/lib/python3.12/site-packages/pip/_vendor/rich/__pycache__/_emoji_codes.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +VRGDG_Musubi-tuner/venv/lib/python3.12/site-packages/pip/_vendor/rich/__pycache__/console.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text diff --git a/VRGDG_Musubi-tuner/.ai/claude.prompt.md b/VRGDG_Musubi-tuner/.ai/claude.prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..729ae53fff144016c1015f40443d5dbda37fada8 --- /dev/null +++ b/VRGDG_Musubi-tuner/.ai/claude.prompt.md @@ -0,0 +1,9 @@ +## About This File + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## 1. Project Context +Here is the essential context for our project. Please read and understand it thoroughly. + +### Project Overview +@./context/overview.md diff --git a/VRGDG_Musubi-tuner/.ai/codex.prompt.md b/VRGDG_Musubi-tuner/.ai/codex.prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..f2901369b265fe32db70788dd72466bbff89e627 --- /dev/null +++ b/VRGDG_Musubi-tuner/.ai/codex.prompt.md @@ -0,0 +1,27 @@ +## About This File + +This file provides guidance to Codex CLI when working with code in this repository. + +## Guidelines + +### Coding Style & Naming Conventions +- Style: PEP 8, 4‑space indentation, limit lines to ~120 chars. +- Naming: snake_case for files/functions (`*_train_network.py`, `*_generate_*`), PascalCase for classes. +- Types/Docs: Prefer type hints for public APIs and short docstrings describing args/returns. +- Formatting: No formatter configured; keep diffs small and consistent with surrounding code. + +### Testing Guidelines +- Current state: No formal test suite. +- If adding tests, use `pytest`, place under `tests/` mirroring `src/musubi_tuner/` and name files `test_*.py`. +- Run (uv): `uv run pytest -q`. Run (pip): `pytest -q`. +- Prefer small, deterministic unit tests around data utilities and argument parsing. + +### Commit & Pull Request Guidelines +- Commits: Use Conventional Commit style seen in history (`feat:`, `fix:`, `doc:`). Write clear, scoped messages. +- PRs: Include a summary, rationale, linked issue(s), and reproduction commands (e.g., the exact `python ... --args`). Add screenshots/log snippets when relevant. +- Docs: Update related files in `docs/` when changing behavior or flags. + +### Security & Configuration Tips +- Large files: Do not commit datasets, model weights, or logs (`logs/` is ignored). Use external storage. +- Credentials: Keep any tokens/keys out of the repo and environment‑specific. +- CUDA: Choose the matching extra (`cu124`, `cu128` or `cu130`) for your driver; verify with `torch.cuda.is_available()`. diff --git a/VRGDG_Musubi-tuner/.ai/context/overview.md b/VRGDG_Musubi-tuner/.ai/context/overview.md new file mode 100644 index 0000000000000000000000000000000000000000..0da4367b98478c2350237f8af8996b5b5e54402f --- /dev/null +++ b/VRGDG_Musubi-tuner/.ai/context/overview.md @@ -0,0 +1,103 @@ +# overview.md + +This file provides guidance to developers when working with code in this repository. + +## Project Overview + +Musubi Tuner is a Python-based training framework for LoRA (Low-Rank Adaptation) models with multiple video generation architectures including HunyuanVideo, HunyuanVideo 1.5, Wan2.1/2.2, FramePack, FLUX.1 Kontext/FLUX.2, Z-Image and Qwen-Image/Qwen-Image-Edit series/Qwen-Image-Layered. The project focuses on memory-efficient training and inference for video generation models. + +## Installation and Environment + +The project uses `pyproject.toml` for dependency management with both pip and uv (experimental) installation methods: + +- **pip installation**: `pip install -e .` after installing PyTorch with CUDA support +- **uv installation**: `uv run --extra cu124` (or `cu128`, `cu130`) (uv installation is experimental) +- **Python requirement**: 3.10 or later (verified with 3.10) +- **PyTorch requirement**: 2.5.1 or later + +Optional dependencies include `ascii-magic`, `matplotlib`, `tensorboard`, and `prompt-toolkit`. + +## Common Development Commands + +### Dataset Preparation +```bash +# Cache latents (required before training) +python src/musubi_tuner/cache_latents.py --dataset_config path/to/toml --vae path/to/vae --vae_chunk_size 32 --vae_tiling + +# Cache text encoder outputs (required before training) +python src/musubi_tuner/cache_text_encoder_outputs.py --dataset_config path/to/toml --text_encoder1 path/to/te1 --text_encoder2 path/to/te2 --batch_size 16 +``` + +`wan_cache_latents.py`, `qwen_image_cache_latents.py` etc. are similar for other architectures. + +### Training Commands +```bash +# HunyuanVideo training +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 src/musubi_tuner/hv_train_network.py --dit path/to/dit --dataset_config path/to/toml --network_module networks.lora --network_dim 32 +``` + +`wan_train_network.py`, `qwen_image_train_network.py` etc. are similar for other architectures. + +Full fine-tuning is also supported for Qwen-Image series with a separate script `qwen_image_train.py` and appropriate arguments. + +### Inference Commands +```bash +# HunyuanVideo inference +python src/musubi_tuner/hv_generate_video.py --fp8 --video_size 544 960 --video_length 5 --prompt "text" --dit path/to/dit --vae path/to/vae +``` + +`wan_generate_video.py`, `qwen_image_generate.py` etc. are similar for other architectures. + +### Utility Commands +```bash +# Merge LoRA weights +python src/musubi_tuner/merge_lora.py --dit path/to/dit --lora_weight path/to/lora.safetensors --save_merged_model path/to/output + +# Convert LoRA formats +python src/musubi_tuner/convert_lora.py --input path/to/lora.safetensors --output path/to/converted.safetensors --target other + +# Post-hoc EMA for LoRA +python src/musubi_tuner/lora_post_hoc_ema.py [args] +``` + +### Testing and Development +No formal test suite is present in this repository. The project relies on manual testing through the training and inference scripts. + +## Code Architecture + +### Core Structure +- `src/musubi_tuner/`: Main package containing all training and inference scripts +- `src/musubi_tuner/dataset/`: Dataset configuration and loading utilities +- `src/musubi_tuner/modules/`: Model architectures and components +- `src/musubi_tuner/networks/`: LoRA network implementations for different architectures +- `src/musubi_tuner/utils/`: Common utilities for model handling, device management, etc. + +### Architecture-Specific Modules +- `hunyuan_model/`: HunyuanVideo model implementation and utilities +- `wan/`: Wan2.1/2.2 model configurations and modules +- `qwen_image/`: Qwen-Image model utilities +- ... and others for FramePack, FLUX, Z-Image + +### Key Components +- **Dataset Configuration**: Uses TOML files for complex dataset setups supporting images, videos, control images, and metadata JSONL files +- **Memory Optimization**: Supports fp8 precision, block swapping, and various attention mechanisms (SDPA, FlashAttention, SageAttention, xformers) +- **Multi-Architecture Support**: Each architecture has its own training/inference scripts with shared utilities +- **LoRA Networks**: Modular LoRA implementations with support for different target modules and configurations + +### Configuration System +- Dataset configuration uses TOML format with support for multiple datasets, bucketing, and architecture-specific settings +- Training configuration via command line arguments and accelerate config +- Support for advanced features like timestep sampling, discrete flow shift, and memory-saving options + +### Memory Management +- Aggressive memory optimization with options like `--blocks_to_swap`, `--fp8_base`, `--fp8_llm` +- VAE tiling or chunking support for handling large resolutions (depending on architecture) +- Gradient checkpointing and mixed precision training +- Block-swap (offloading weights to CPU) for large models + +## Development Notes +- The project is under active development with experimental features +- No formal CI/CD or automated testing +- Uses accelerate for distributed training setup +- Supports both interactive and batch inference modes +- Comprehensive documentation in `docs/` directory for advanced configurations and architecture-specific guides \ No newline at end of file diff --git a/VRGDG_Musubi-tuner/.ai/gemini.prompt.md b/VRGDG_Musubi-tuner/.ai/gemini.prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..9ea380193854a9f3d66f049859816b722d527a5d --- /dev/null +++ b/VRGDG_Musubi-tuner/.ai/gemini.prompt.md @@ -0,0 +1,9 @@ +## About This File + +This file provides guidance to Gemini CLI (https://github.com/google-gemini/gemini-cli) when working with code in this repository. + +## 1. Project Context +Here is the essential context for our project. Please read and understand it thoroughly. + +### Project Overview +@./context/overview.md diff --git a/VRGDG_Musubi-tuner/.github/FUNDING.yml b/VRGDG_Musubi-tuner/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..5b08f44140f62bf2cca4cc5c0770ca320607dbca --- /dev/null +++ b/VRGDG_Musubi-tuner/.github/FUNDING.yml @@ -0,0 +1,3 @@ +# These are supported funding model platforms + +github: kohya-ss diff --git a/VRGDG_Musubi-tuner/.github/workflows/ruff-lint.yml b/VRGDG_Musubi-tuner/.github/workflows/ruff-lint.yml new file mode 100644 index 0000000000000000000000000000000000000000..3b2a9120e28c7ac1019817c1095ede044afb98c9 --- /dev/null +++ b/VRGDG_Musubi-tuner/.github/workflows/ruff-lint.yml @@ -0,0 +1,48 @@ +name: Ruff Lint + +on: + pull_request: + branches: + - main + push: + paths: + - "src/musubi_tuner/**/*.py" + - "src/musubi_tuner/**/*.pth" + - ".python-version" + - "pyproject.toml" + workflow_dispatch: + +jobs: + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: "Set up Python" + uses: actions/setup-python@v5 + with: + python-version-file: ".python-version" + + - name: "Install uv" + uses: astral-sh/setup-uv@v6 + with: + enable-cache: true + + - name: Install the project + run: uv sync --dev + + - name: "Run Ruff check" + uses: astral-sh/ruff-action@v3 + with: + args: > + check --fix + + - name: "Run Ruff format check" + uses: astral-sh/ruff-action@v3 + with: + args: > + format --check + # will exit with a non-zero code if there are formatting changes + + # - name: Minimize uv cache + # run: uv cache prune --ci diff --git a/VRGDG_Musubi-tuner/.gitignore b/VRGDG_Musubi-tuner/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..89a041bc40f39bec2989244c7843f193ab0b31d6 --- /dev/null +++ b/VRGDG_Musubi-tuner/.gitignore @@ -0,0 +1,18 @@ +__pycache__/ +.venv +venv/ +logs/ +uv.lock +main.exp +main.lib +main.obj +CLAUDE.md +GEMINI.md +.claude/ +.gemini/ +AGENTS.md +.vscode/settings.json +.mcp.json +references/ +projects/ +tests/ \ No newline at end of file diff --git a/VRGDG_Musubi-tuner/.pre-commit-config.yaml b/VRGDG_Musubi-tuner/.pre-commit-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2872e23c882783e1342b9cc1b60a5e0c8f0e07a8 --- /dev/null +++ b/VRGDG_Musubi-tuner/.pre-commit-config.yaml @@ -0,0 +1,7 @@ +repos: + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.15.2 + hooks: + - id: ruff-check + args: [--fix] + - id: ruff-format diff --git a/VRGDG_Musubi-tuner/.python-version b/VRGDG_Musubi-tuner/.python-version new file mode 100644 index 0000000000000000000000000000000000000000..c8cfe3959183f8e9a50f83f54cd723f2dc9c252d --- /dev/null +++ b/VRGDG_Musubi-tuner/.python-version @@ -0,0 +1 @@ +3.10 diff --git a/VRGDG_Musubi-tuner/CONTRIBUTING.ja.md b/VRGDG_Musubi-tuner/CONTRIBUTING.ja.md new file mode 100644 index 0000000000000000000000000000000000000000..0f21f7ad7ea56f52a098f92a262c0ca5c7e1d594 --- /dev/null +++ b/VRGDG_Musubi-tuner/CONTRIBUTING.ja.md @@ -0,0 +1,319 @@ +# Musubi Tuner へのコントリビューション + +Musubi Tuner 開発へのご支援、ご協力に感謝いたします。コミュニティからの開発へ手助けは、このプロジェクトにとって不可欠です。このドキュメントでは、コントリビューションの方法やプロジェクトへの参加方法について説明します。 + +## 目次 + +- [はじめに](#はじめに) +- [ご協力いただく前に](#ご協力いただく前に) +- [プロジェクトへの協力の方法](#プロジェクトへの協力の方法) + - [問題の報告](#問題の報告) + - [機能の提案](#機能の提案) + - [コードのコントリビューション](#コードのコントリビューション) +- [開発環境のセットアップ](#開発環境のセットアップ) +- [コードスタイルとガイドライン](#コードスタイルとガイドライン) +- [テスト](#テスト) +- [プルリクエストのプロセス](#プルリクエストのプロセス) +- [ライセンスと帰属(Attribution)](#ライセンスと帰属attribution) +- [コミュニティとサポート](#コミュニティとサポート) + +## はじめに + +開発にご協力いただく前に以下をお願いします: + +1. このドキュメントを読む +2. [README.md](README.md) でプロジェクトを理解する +3. [既存の Issue](https://github.com/kohya-ss/musubi-tuner/issues) と [ディスカッション](https://github.com/kohya-ss/musubi-tuner/discussions) を確認する +4. 開発環境をセットアップする + +## ご協力いただく前に + +### ご留意いただきたい点 + +- このプロジェクトのメンテナンスは限られた時間とリソースで行われています +- PRのレビューとマージには時間がかかる場合があります +- プロジェクトが成長する過程で破壊的変更が発生する可能性があります +- 質問や一般的な議論には [GitHub Discussions](https://github.com/kohya-ss/musubi-tuner/discussions) をご利用ください +- バグ報告や機能要求には [GitHub Issues](https://github.com/kohya-ss/musubi-tuner/issues) をご利用ください + +### ご協力いただける例 + +- バグ修正 +- パフォーマンスの改善 +- ドキュメントの改善 +- 新機能の追加(事前にディスカッションを行うことを推奨) +- コード品質の改善 + +## プロジェクトへの協力の方法 + +### 問題の報告 + +新しい Issue を作成する前に: + +1. **既存の Issue を検索**して重複を避けてください +2. **ディスカッションを確認**して、質問が既に回答されていないか確認してください + +バグ報告を作成する際は以下を含めてください: + +- **明確で内容を適切に要約したタイトル** +- **問題の詳細な説明** +- **問題を再現する手順** +- **環境の詳細**: + - オペレーティングシステム + - GPU モデルと VRAM + - Python バージョン + - PyTorch バージョン + - CUDA バージョン +- **エラーメッセージやログ** +- **期待される動作と実際の動作** +- **スクリーンショットや動画**(必要な場合) + +### 機能の提案 + +機能要求の場合: + +1. **まず Issue を開いて**機能について議論してください +2. **機能が解決する問題を説明**します +3. **提案された解決策を説明**します +4. **代替案とそのトレードオフ**を検討してください +5. **実装前にフィードバックを待つ**ことをお願いします(PRがマージされない可能性は常にあります) + +重要な機能については、まず [GitHub Discussions](https://github.com/kohya-ss/musubi-tuner/discussions) にコミュニティの意見を求めることを検討してください。 + +### コードのコントリビューション + +1. **Issue を開いて**提案する変更について議論をお願いします(些細な修正ではない場合) +2. **重要な変更の作業を開始する前に承認を待つ**ことをお願いします +3. **リポジトリをフォーク**して機能ブランチを作成する +4. **コードスタイルガイドライン**に従って変更を行う +5. **変更を徹底的にテスト**する +6. **プルリクエストを提出**する + +## 開発環境のセットアップ + +### 前提条件 + +- Python 3.10 以上 +- Git +- CUDA 対応 GPU(GPU 機能のテスト用) +- 12GB 以上の VRAM 推奨 + +### インストール + +1. **リポジトリをフォークしてクローン**: + ```shell + git clone https://github.com/your-username/musubi-tuner.git + cd musubi-tuner + ``` + +2. **開発環境をセットアップ**: + + **オプション A: pip を使用** + ```shell + # 仮想環境を作成 + python -m venv .venv + + # 仮想環境をアクティベート + # Windows の場合: + .venv/Scripts/activate + # Linux/Mac の場合: + source .venv/bin/activate + + # PyTorch をインストール(CUDA バージョンに合わせて調整) + pip install torch torchvision --index-url https://download.pytorch.org/whl/cu128 + + # パッケージを開発モードでインストール + pip install -e . + + # 開発依存関係をインストール + pip install --group dev + ``` + + **オプション B: uv を使用** + ```shell + # uv がインストールされていない場合はインストール + curl -LsSf https://astral.sh/uv/install.sh | sh # Linux/Mac + # または + powershell -c "irm https://astral.sh/uv/install.ps1 | iex" # Windows + + # 依存関係をインストール + uv sync --extra cu128 # または CUDA バージョンにより cu124 + ``` + +3. **Accelerate を設定**: + ```shell + accelerate config + ``` + +## コードスタイルとガイドライン + +### Python コードスタイル + +このプロジェクトは **Ruff** をコード解析(リンティング)とコード整形に使用しています: + +- **行の長さ**: 132 文字 +- **インデント**: 4 スペース +- **クォートスタイル**: ダブルクォート +- **対象 Python バージョン**: 3.10 + +### IDE のセットアップ + +https://docs.astral.sh/ruff/editors/setup/ + +### コード解析、整形の実行 + +```shell +# コードスタイルと潜在的な問題をチェック +ruff check + +# 可能な場合は自動修正 +ruff check --fix + +# コードをフォーマット(注: フォーマットには black ではなく ruff を使用してください) +ruff format src +``` + +### コードガイドライン + +- **コードベースの既存パターン**に従う +- **明確で説明的な変数名**を書く +- **適切な場所で型ヒント**を追加する +- **関数を単一の機能で適度なサイズ**に保つ +- **パブリック関数とクラスにドキュメント文字列**を追加する +- **エラーを適切に処理**: 回復不可能なエラーはそのままエラーとし、適切な対応が可能なエラーのみをキャッチして処理する + +### インポートの整理 + +- 標準ライブラリのインポートを最初に +- サードパーティのインポートを次に +- ローカルインポートを最後に +- 可能な限り絶対インポートを使用 + +### コード修正ガイドライン + +既存のコードを扱う場合: + +- **既存のインターフェースとの互換性を維持**する +- **既存のモジュール構造に従う** +- **`docs/` ディレクトリの関連ドキュメントを更新**する +- **変更が複数のシステムに影響する場合、能力があれば異なるアーキテクチャでテスト**する + +アーキテクチャ固有のコード(HunyuanVideo、Wan2.1/2.2、FramePack、FLUX.1 Kontext、Qwen-Image)を扱う場合: + +- **命名規則に従う**: 新しいアーキテクチャを追加する場合は `{arch}_train_network.py` と `{arch}_generate_{type}.py` の命名パターンに従う +- **アーキテクチャ間の影響を考慮する**: アーキテクチャ間で共有されるコードを変更する場合 +- **他のアーキテクチャでのテスト**: 変更が他のアーキテクチャに影響する場合、可能であればそれらでもテストする + +## テスト + +### テストの実行 + +```shell +# コード品質チェックを実行 +ruff check + +# コードをフォーマット +ruff format src + +# 関連するスクリプトで変更を手動テスト +``` + +### 手動テストガイドライン + +このプロジェクトは機械学習モデルを扱っています。そのため: + +1. **まず小さなデータセット**で始めてください +2. **メモリ使用量が期待する範囲内**であることを確認してください +3. **可能であれば異なる GPU 構成**でテストをお願いします +4. **生成/訓練機能の出力品質**を検証してください + +## プルリクエストのプロセス + +### 提出前 + +1. **当該ブランチが最新のメインブランチと同期**していることを確認してください +2. **コード品質ツールを実行**: + ```shell + ruff check --fix + ruff format src + ``` +3. **変更を徹底的にテスト**します +4. **必要に応じてドキュメントを更新**してください +5. **明確なコミットメッセージ**を書いてください + +### プルリクエストテンプレート + +PR を作成する際は以下を含めてください: + +- **変更を説明する明確なタイトル** +- **何が変更されたか、なぜかの説明** +- **Issue への参照**(例:「Closes #123」) +- **実行されたテスト** +- **破壊的変更**(もしある場合) +- **ドキュメントの更新**(もしある場合) + +### レビュープロセス + +- メンテナーは時間があるときに PR をレビューします +- 限られたリソースのためレビューに時間がかかる場合がありますが、ご了承ください +- フィードバックに建設的に対処してください +- 議論を集中的かつ専門的に保つようお願いします + +## ライセンスと帰属(Attribution) + +### 帰属の要件 + +他のプロジェクトから派生または着想を得たコードを追加する場合: + +1. **新しいファイルに適切なライセンスヘッダー**を追加する +2. **コピー/修正されたコードに帰属コメント**を含める +3. 新しいアーキテクチャのために**新しいライセンス要求を導入する場合は README.md の LICENSE セクションを更新**する +4. **プルリクエストの説明で参照元を文書化**する + +### サードパーティのコード + +あなたのコントリビューションにサードパーティのコードが含まれる場合: + +1. **プロジェクトとのライセンス互換性を確保**する +2. **元のライセンスファイルまたはヘッダーを含める** +3. **ソースとライセンスを明確に文書化**する。プルリクエストの説明にも記載してください +4. **ソースライセンスからのすべての義務を履行**する + +## コミュニティとサポート + +### 情報交換の手段 + +- **GitHub Discussions**: 一般的な質問、アイデア、コミュニティの交流 +- **GitHub Issues**: バグ報告と機能要求 +- **Pull Requests**: コード貢献とレビュー + +### 何かわからないことがあれば + +内容に応じて以下の方法で質問してください: + +- **ソフトウェアの使用法など**: [GitHub Discussions](https://github.com/kohya-ss/musubi-tuner/discussions) をチェックしてください +- **開発環境のセットアップ**: 「question」ラベルで Issue を作成してするか、ディスカッションで質問してください +- **コントリビューションのプロセス**: このガイドを参照するか、ディスカッションで質問してください + +### ご協力いただいた方への謝辞など + +ご協力いただいた方は以下の方法等でご紹介させていただきます: + +- **Git コミット履歴** +- **重要なコントリビューションのリリースノート** +- **主要な機能への README での謝辞** + +--- + +## 最終に + +Musubi Tuner へのご協力に興味をお持ちいただき、ありがとうございます。このプロジェクトはコミュニティのご支援、ご協力で成り立っています。 + +以下についてご留意いただければ幸いです: + +- **最初のコントリビューションは小さく**始めることをお勧めします +- **何か不明な点があれば質問**してください +- **レビュープロセスは辛抱強く**お待ちいただければ幸いです +- **ツールの構築と改善に一緒に取り組めればと**考えています + +皆様のMusubi Tuner へのご協力に重ねて感謝申し上げます。 \ No newline at end of file diff --git a/VRGDG_Musubi-tuner/CONTRIBUTING.md b/VRGDG_Musubi-tuner/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..e9a3c67e81d98c7d8f9337d9ee81c27cb6c48894 --- /dev/null +++ b/VRGDG_Musubi-tuner/CONTRIBUTING.md @@ -0,0 +1,318 @@ +# Contributing to Musubi Tuner + +Thank you for your interest in contributing to Musubi Tuner! We welcome contributions from the community and are excited to work with you to make this project even better. + +## Table of Contents + +- [Getting Started](#getting-started) +- [Before You Contribute](#before-you-contribute) +- [How to Contribute](#how-to-contribute) + - [Reporting Issues](#reporting-issues) + - [Suggesting Features](#suggesting-features) + - [Contributing Code](#contributing-code) +- [Development Setup](#development-setup) +- [Code Style and Guidelines](#code-style-and-guidelines) +- [Testing](#testing) +- [Pull Request Process](#pull-request-process) +- [Licensing and Attribution](#licensing-and-attribution) +- [Community and Support](#community-and-support) + +## Getting Started + +Before contributing, please: + +1. Read through this contributing guide +2. Review the [README.md](README.md) to understand the project +3. Check the [existing issues](https://github.com/kohya-ss/musubi-tuner/issues) and [discussions](https://github.com/kohya-ss/musubi-tuner/discussions) +4. Set up your development environment + +## Before You Contribute + +### Important Notes + +- This project is under active development with limited maintainer resources +- PR reviews and merges may take time +- Breaking changes may occur as the project evolves +- For questions and general discussion, use [GitHub Discussions](https://github.com/kohya-ss/musubi-tuner/discussions) +- For bug reports and feature requests, use [GitHub Issues](https://github.com/kohya-ss/musubi-tuner/issues) + +### Types of Contributions We Welcome + +- Bug fixes +- Performance improvements +- Documentation improvements +- New features (with prior discussion) +- Code quality improvements + +## How to Contribute + +### Reporting Issues + +Before creating a new issue: + +1. **Search existing issues** to avoid duplicates +2. **Check discussions** as your question might already be answered + +When creating a bug report, include: + +- **Clear, descriptive title** +- **Detailed description** of the problem +- **Steps to reproduce** the issue +- **Environment details**: + - Operating System + - GPU model and VRAM + - Python version + - PyTorch version + - CUDA version +- **Error messages or logs** +- **Expected vs actual behavior** +- **Screenshots or videos** (if applicable) + +### Suggesting Features + +For feature requests: + +1. **Open an issue first** to discuss the feature +2. **Explain the problem** your feature would solve +3. **Describe the proposed solution** +4. **Consider alternatives** and their trade-offs +5. **Wait for feedback** before starting implementation (there's always a chance the PR won't be merged) + +For significant features, consider posting in [GitHub Discussions](https://github.com/kohya-ss/musubi-tuner/discussions) first to gather community input. + +### Contributing Code + +1. **Open an issue** to discuss your proposed changes (unless it's a trivial fix) +2. **Wait for approval** before starting work on significant changes +3. **Fork the repository** and create a feature branch +4. **Make your changes** following our code style guidelines +5. **Test your changes** thoroughly +6. **Submit a pull request** + +## Development Setup + +### Prerequisites + +- Python 3.10 or later +- Git +- CUDA-compatible GPU (for testing GPU features) +- 12GB+ VRAM recommended + +### Installation + +1. **Fork and clone the repository**: + ```shell + git clone https://github.com/your-username/musubi-tuner.git + cd musubi-tuner + ``` + +2. **Set up the development environment**: + + **Option A: Using pip** + ```shell + # Create virtual environment + python -m venv .venv + + # Activate virtual environment + # On Windows: + .venv/Scripts/activate + # On Linux/Mac: + source .venv/bin/activate + + # Install PyTorch (adjust for your CUDA version) + pip install torch torchvision --index-url https://download.pytorch.org/whl/cu128 + + # Install the package in development mode + pip install -e . + + # Install development dependencies + pip install --group dev + ``` + + **Option B: Using uv** + ```shell + # Install uv if not present + curl -LsSf https://astral.sh/uv/install.sh | sh # Linux/Mac + # or + powershell -c "irm https://astral.sh/uv/install.ps1 | iex" # Windows + + # Install dependencies + uv sync --extra cu128 # or cu124 based on your CUDA version + ``` + +3. **Configure Accelerate**: + ```shell + accelerate config + ``` + +## Code Style and Guidelines + +### Python Code Style + +This project uses **Ruff** for code linting and code formatting: + +- **Line length**: 132 characters +- **Indentation**: 4 spaces +- **Quote style**: Double quotes +- **Target Python version**: 3.10 + +### IDE + +https://docs.astral.sh/ruff/editors/setup/ + +### Running Code Quality Tools + +```shell +# Check code style and potential issues +ruff check + +# Auto-fix issues where possible +ruff check --fix + +# Format code (note: use ruff for formatting, not black) +ruff format src +``` + +### Code Guidelines + +- **Follow existing patterns** in the codebase +- **Write clear, descriptive variable names** +- **Add type hints** where appropriate +- **Keep functions focused** and reasonably sized +- **Add docstrings** for public functions and classes +- **Handle errors appropriately** - Let unrecoverable errors fail fast; only catch and handle errors you can meaningfully recover from + +### Import Organization + +- Standard library imports first +- Third-party imports second +- Local imports last +- Use absolute imports when possible + +### Code Modification Guidelines + +When working with existing code: + +- **Maintain compatibility** with existing interfaces +- **Follow the existing module structure** +- **Update relevant documentation** in the `docs/` directory +- **Test across different architectures** if your changes affect multiple architectures and you have the capability to do so + +When working with architecture-specific code (HunyuanVideo, Wan2.1/2.2, FramePack, FLUX.1 Kontext, Qwen-Image): + +- **Follow naming conventions**: When adding a new architecture, follow the `{arch}_train_network.py` and `{arch}_generate_{type}.py` naming pattern +- **Consider cross-architecture impact** when making changes within shared modules +- **Test with representative models** if possible + +## Testing + +### Running Tests + +```shell +# Run code quality checks +ruff check + +# Format code +ruff format src + +# Test your changes manually with the relevant scripts +``` + +### Manual Testing Guidelines + +Since this project deals with machine learning models: + +1. **Test with small datasets** first +2. **Verify memory usage** is within expected boundaries +3. **Test on different GPU configurations** if possible +4. **Validate output quality** for generation/training features + +## Pull Request Process + +### Before Submitting + +1. **Ensure your branch is up to date** with the main branch +2. **Run code quality tools**: + ```shell + ruff check --fix + ruff format src + ``` +3. **Test your changes** thoroughly +4. **Update documentation** if needed +5. **Write clear commit messages** + +### Pull Request Template + +When creating a PR, include: + +- **Clear title** describing the change +- **Description** of what changed and why +- **Issue reference** (e.g., "Closes #123") +- **Testing performed** +- **Breaking changes** (if any) +- **Documentation updates** (if any) + +### Review Process + +- Maintainers will review PRs when time permit +- Be patient as reviews may take time due to limited resources +- Address feedback constructively +- Keep discussions focused and professional + +## Licensing and Attribution + +### Attribution Requirements + +When contributing code derived from or inspired by other projects: + +1. **Add appropriate license headers** to new files +2. **Include attribution comments** for copied/modified code +3. **Update the LICENSE section on README.md** if introducing new license requirements for new architectures +4. **Document the source** in your pull request description + +### Third-Party Code + +If your contribution includes third-party code: + +1. **Ensure license compatibility** with the project +2. **Include the original license file** or header +3. **Document the source and license** clearly. Incorporate this in your pull request description as well +4. **Fulfill all obligations** from the source license + +## Community and Support + +### Communication Channels + +- **GitHub Discussions**: General questions, ideas, and community interaction +- **GitHub Issues**: Bug reports and feature requests +- **Pull Requests**: Code contributions and reviews + +### Getting Help + +If you need help with: + +- **Using the software**: Check [GitHub Discussions](https://github.com/kohya-ss/musubi-tuner/discussions) +- **Development setup**: Create an issue with the "question" label or ask in discussions +- **Contributing process**: Reference this guide or ask in discussions + +### Recognition + +Contributors are recognized through: + +- **Git commit history** +- **Release notes** for significant contributions +- **README acknowledgments** for major features + +--- + +## Final Notes + +We appreciate your interest in contributing to Musubi Tuner! This project benefits greatly from community contributions, and we're grateful for your time and effort. + +Remember: +- **Start small** with your first contribution +- **Ask questions** if anything is unclear +- **Be patient** with the review process +- **Have fun** building amazing tools! + +Thank you for helping make Musubi Tuner better for everyone! diff --git a/VRGDG_Musubi-tuner/README.ja.md b/VRGDG_Musubi-tuner/README.ja.md new file mode 100644 index 0000000000000000000000000000000000000000..8f98fbc1bec3416d93a728899ceffd37f879c84f --- /dev/null +++ b/VRGDG_Musubi-tuner/README.ja.md @@ -0,0 +1,314 @@ +# Musubi Tuner + +[English](./README.md) | [日本語](./README.ja.md) + +## 目次 + +
+クリックすると展開します + +- [はじめに](#はじめに) + - [スポンサー](#スポンサー) + - [スポンサー募集のお知らせ](#スポンサー募集のお知らせ) + - [最近の更新](#最近の更新) + - [リリースについて](#リリースについて) + - [AIコーディングエージェントを使用する開発者の方へ](#AIコーディングエージェントを使用する開発者の方へ) +- [概要](#概要) + - [ハードウェア要件](#ハードウェア要件) + - [特徴](#特徴) + - [ドキュメント](#ドキュメント) +- [インストール](#インストール) + - [pipによるインストール](#pipによるインストール) + - [uvによるインストール](#uvによるインストール) + - [Linux/MacOS](#linuxmacos) + - [Windows](#windows) +- [モデルのダウンロード](#モデルのダウンロード) +- [使い方](#使い方) + - [データセット設定](#データセット設定) + - [事前キャッシュと学習](#事前キャッシュと学習) + - [Accelerateの設定](#Accelerateの設定) + - [学習と推論](#学習と推論) +- [その他](#その他) + - [SageAttentionのインストール方法](#SageAttentionのインストール方法) + - [PyTorchのバージョンについて](#PyTorchのバージョンについて) +- [免責事項](#免責事項) +- [コントリビューションについて](#コントリビューションについて) +- [ライセンス](#ライセンス) +
+ +## はじめに + +このリポジトリは、HunyuanVideo、Wan2.1/2.2、FramePack、FLUX.1 Kontext、FLUX.2 dev/klein、Qwen-Image、Z-Image、および [LTX-2](./docs/ltx_2.md)のLoRA学習用のコマンドラインツールです。このリポジトリは非公式であり、それらの公式リポジトリとは関係ありません。 + +*リポジトリは開発中です。* + +### スポンサー + +このプロジェクトを支援してくださる企業・団体の皆様に深く感謝いたします。 + + + AiHUB株式会社 + + +### スポンサー募集のお知らせ + +このプロジェクトがお役に立ったなら、ご支援いただけると嬉しく思います。 [GitHub Sponsors](https://github.com/sponsors/kohya-ss/)で受け付けています。 + +### 最近の更新 + +GitHub Discussionsを有効にしました。コミュニティのQ&A、知識共有、技術情報の交換などにご利用ください。バグ報告や機能リクエストにはIssuesを、質問や経験の共有にはDiscussionsをご利用ください。[Discussionはこちら](https://github.com/kohya-ss/musubi-tuner/discussions) + +- 2026/02/15 + - LoHa/LoKrの学習に対応しました。[PR #900](https://github.com/kohya-ss/musubi-tuner/pull/900) + - LyCORISのLoHa/LoKrアルゴリズムに基づいて実装されています。LyCORISプロジェクトのKohakuBlueleaf氏に深く感謝します。 + - 詳細は[ドキュメント](./docs/loha_lokr.md)を参照してください。 + - Z-Imageのfine-tuningで、blocks_to_swapを使用している場合に、一部のオプティマイザを使用可能にする`--block_swap_optimizer_patch_params`オプションを追加しました。[PR #899](https://github.com/kohya-ss/musubi-tuner/pull/899) + - 詳細は[ドキュメント](./docs/zimage.md#finetuning)を参照してください。 + +- 2026/01/29 + - Z-Image-Baseのリリースに伴いLoRA、finetuningの動作確認を行い、共に動作することを確認しました。 + - Z-Imageの[関連ドキュメント](./docs/zimage.md)を修正しました。 + - またZ-ImageのLoRA学習、finetuningでサンプル画像生成が正しく動作しなかったのを修正しました。以上は[PR #861](https://github.com/kohya-ss/musubi-tuner/pull/861) + +- 2026/01/24 + - FLUX.2 [klein]のLoRA学習が動かなかったのを修正しました。またFLUX.2に関する各種の不具合修正、機能追加を行いました。[PR #858](https://github.com/kohya-ss/musubi-tuner/pull/858) + - `--model_version`の指定は`flux.2-dev`や`flux.2-klein-4b`等から、`dev`や`klein-4b`等に変更されました。 + - fp8最適化なども動作します。詳細は[ドキュメント](./docs/flux_2.md)を参照してください。 + - klein 9B、devモデル、および複数枚の制御画像を用いた学習は十分にテストされていないため、不具合があればIssueで報告してください。 + +- 2026/01/21 + - FLUX.2 [dev]/[klein]のLoRA学習に対応しました。[PR #841](https://github.com/kohya-ss/musubi-tuner/pull/841) https://www.scenario.com のchristopher5106氏に深く感謝します。 + - 詳細は[ドキュメント](./docs/flux_2.md)を参照してください。 + +- 2026/01/17 + - Z-ImageのComfyUI向けのLoRA変換について、互換性向上のため `convert_lora.py` を使用するように変更しました。[PR #851](https://github.com/kohya-ss/musubi-tuner/pull/851) + - 以前の `convert_z_image_lora_to_comfy.py` も引き続き使用可能ですが、nunchakuで正しく動作しない可能性があります。 + - 詳細は[ドキュメント](./docs/zimage.md#converting-lora-weights-to-diffusers-format-for-comfyui--lora重みをcomfyuiで使用可能なdiffusers形式に変換する)を参照してください。 + - [Issue #847](https://github.com/kohya-ss/musubi-tuner/issues/847) で解決策を提供してくださったfai-9氏に感謝します。 + - Qwen-Image-LayeredのLoRA学習で、元画像を学習対象から除外するオプション `--remove_first_image_from_target` を追加しました。[PR #852](https://github.com/kohya-ss/musubi-tuner/pull/852) + - 詳細は[ドキュメント](./docs/qwen_image.md#lora-training--lora学習)を参照してください。 + +- 2026/01/11 + - Qwen-Image-LayeredのLoRA学習に対応しました。[PR #816](https://github.com/kohya-ss/musubi-tuner/pull/816) + - 詳細は[ドキュメント](./docs/qwen_image.md)を参照してください。 + - キャッシュ作成、学習、推論の各スクリプトで、`--model_version` オプションに `layered` を指定してください。 + +### リリースについて + +Musubi Tunerの解説記事執筆や、関連ツールの開発に取り組んでくださる方々に感謝いたします。このプロジェクトは開発中のため、互換性のない変更や機能追加が起きる可能性があります。想定外の互換性問題を避けるため、参照用として[リリース](https://github.com/kohya-ss/musubi-tuner/releases)をお使いください。 + +最新のリリースとバージョン履歴は[リリースページ](https://github.com/kohya-ss/musubi-tuner/releases)で確認できます。 + +### AIコーディングエージェントを使用する開発者の方へ + +このリポジトリでは、ClaudeやGeminiのようなAIエージェントが、プロジェクトの概要や構造を理解しやすくするためのエージェント向け文書(プロンプト)を用意しています。 + +これらを使用するためには、プロジェクトのルートディレクトリに各エージェント向けの設定ファイルを作成し、明示的に読み込む必要があります。 + +**セットアップ手順:** + +1. プロジェクトのルートに `CLAUDE.md` や `GEMINI.md`、`AGENTS.md` ファイルを作成します。 +2. `CLAUDE.md` 等に以下の行を追加して、リポジトリが推奨するプロンプトをインポートします(現在、両者はほぼ同じ内容です): + + ```markdown + @./.ai/claude.prompt.md + ``` + + Geminiの場合はこちらです: + + ```markdown + @./.ai/gemini.prompt.md + ``` + + 他のエージェント向けの設定ファイルでもそれぞれの方法でインポートしてください。 + +3. インポートした行の後に、必要な指示を適宜追加してください(例:`Always respond in Japanese.`)。 + +このアプローチにより、共有されたプロジェクトのコンテキストを活用しつつ、エージェントに与える指示を各ユーザーが自由に制御できます。`CLAUDE.md`、`GEMINI.md` および `AGENTS.md` (またClaude用の `.mcp.json`)はすでに `.gitignore` に記載されているため、リポジトリにコミットされることはありません。 + +## 概要 + +### ハードウェア要件 + +- VRAM: 静止画での学習は12GB以上推奨、動画での学習は24GB以上推奨。 + - *アーキテクチャ、解像度等の学習設定により異なります。*12GBでは解像度 960x544 以下とし、`--blocks_to_swap`、`--fp8_llm`等の省メモリオプションを使用してください。 +- メインメモリ: 64GB以上を推奨、32GB+スワップで動作するかもしれませんが、未検証です。 + +### 特徴 + +- 省メモリに特化 +- Windows対応(Linuxでの動作報告もあります) +- マルチGPU学習([Accelerate](https://huggingface.co/docs/accelerate/index)を使用)、ドキュメントは後日追加予定 + +### ドキュメント + +各アーキテクチャの詳細、設定、高度な機能については、以下のドキュメントを参照してください。 + +**アーキテクチャ別:** +- [HunyuanVideo](./docs/hunyuan_video.md) +- [Wan2.1/2.2](./docs/wan.md) +- [Wan2.1/2.2 (1フレーム推論)](./docs/wan_1f.md) +- [FramePack](./docs/framepack.md) +- [FramePack (1フレーム推論)](./docs/framepack_1f.md) +- [FLUX.1 Kontext](./docs/flux_kontext.md) +- [Qwen-Image](./docs/qwen_image.md) +- [Z-Image](./docs/zimage.md) +- [HunyuanVideo 1.5](./docs/hunyuan_video_1_5.md) +- [Kandinsky 5](./docs/kandinsky5.md) +- [LTX-2](./docs/ltx_2.md) +- [FLUX.2](./docs/flux_2.md) + +**共通設定・その他:** +- [データセット設定](./docs/dataset_config.md) +- [高度な設定](./docs/advanced_config.md) +- [学習中のサンプル生成](./docs/sampling_during_training.md) +- [ツールとユーティリティ](./docs/tools.md) +- [torch.compileの使用方法](./docs/torch_compile.md) + +## インストール + +### pipによるインストール + +Python 3.10以上を使用してください(3.10で動作確認済み)。 + +適当な仮想環境を作成し、ご利用のCUDAバージョンに合わせたPyTorchとtorchvisionをインストールしてください。 + +PyTorchはバージョン2.5.1以上を使用してください([補足](#PyTorchのバージョンについて))。 + +```bash +pip install torch torchvision --index-url https://download.pytorch.org/whl/cu124 +``` + +以下のコマンドを使用して、必要な依存関係をインストールします。 + +```bash +pip install -e . +``` + +オプションとして、FlashAttention、SageAttention(**推論にのみ使用できます**、インストール方法は[こちら](#SageAttentionのインストール方法)を参照)を使用できます。 + +また、`ascii-magic`(データセットの確認に使用)、`matplotlib`(timestepsの可視化に使用)、`tensorboard`(学習ログの記録に使用)、`prompt-toolkit`を必要に応じてインストールしてください。 + +`prompt-toolkit`をインストールするとWan2.1およびFramePackのinteractive modeでの編集に、自動的に使用されます。特にLinux環境でプロンプトの編集が容易になります。 + +```bash +pip install ascii-magic matplotlib tensorboard prompt-toolkit +``` + +### uvによるインストール + +uvを使用してインストールすることもできますが、uvによるインストールは試験的なものです。フィードバックを歓迎します。 + +#### Linux/MacOS + +```sh +curl -LsSf https://astral.sh/uv/install.sh | sh +``` + +表示される指示に従い、pathを設定してください。 + +#### Windows + +```powershell +powershell -c "irm https://astral.sh/uv/install.ps1 | iex" +``` + +表示される指示に従い、PATHを設定するか、この時点でシステムを再起動してください。 + +## モデルのダウンロード + +モデルのダウンロード手順はアーキテクチャによって異なります。詳細は[ドキュメント](#ドキュメント)セクションにある、各アーキテクチャのドキュメントを参照してください。 + +## 使い方 + +### データセット設定 + +[こちら](./docs/dataset_config.md)を参照してください。 + +### 事前キャッシュ + +事前キャッシュの手順の詳細は、[ドキュメント](#ドキュメント)セクションにある各アーキテクチャのドキュメントを参照してください。 + +### Accelerateの設定 + +`accelerate config`を実行して、Accelerateの設定を行います。それぞれの質問に、環境に応じた適切な値を選択してください(値を直接入力するか、矢印キーとエンターで選択、大文字がデフォルトなので、デフォルト値でよい場合は何も入力せずエンター)。GPU 1台での学習の場合、以下のように答えてください。 + +```txt +- In which compute environment are you running?: This machine +- Which type of machine are you using?: No distributed training +- Do you want to run your training on CPU only (even if a GPU / Apple Silicon / Ascend NPU device is available)?[yes/NO]: NO +- Do you wish to optimize your script with torch dynamo?[yes/NO]: NO +- Do you want to use DeepSpeed? [yes/NO]: NO +- What GPU(s) (by id) should be used for training on this machine as a comma-seperated list? [all]: all +- Would you like to enable numa efficiency? (Currently only supported on NVIDIA hardware). [yes/NO]: NO +- Do you wish to use mixed precision?: bf16 +``` + +※場合によって ``ValueError: fp16 mixed precision requires a GPU`` というエラーが出ることがあるようです。この場合、6番目の質問( +``What GPU(s) (by id) should be used for training on this machine as a comma-separated list? [all]:``)に「0」と答えてください。(id `0`、つまり1台目のGPUが使われます。) + +### 学習と推論 + +学習と推論の手順はアーキテクチャによって大きく異なります。詳細な手順については、[ドキュメント](#ドキュメント)セクションにある対応するアーキテクチャのドキュメント、および各種の設定のドキュメントを参照してください。 + +## その他 + +### SageAttentionのインストール方法 + +sdbds氏によるWindows対応のSageAttentionのwheelが https://github.com/sdbds/SageAttention-for-windows で公開されています。triton をインストールし、Python、PyTorch、CUDAのバージョンが一致する場合は、[Releases](https://github.com/sdbds/SageAttention-for-windows/releases)からビルド済みwheelをダウンロードしてインストールすることが可能です。sdbds氏に感謝します。 + +参考までに、以下は、SageAttentionをビルドしインストールするための簡単な手順です。Microsoft Visual C++ 再頒布可能パッケージを最新にする必要があるかもしれません。 + +1. Pythonのバージョンに応じたtriton 3.1.0のwhellを[こちら](https://github.com/woct0rdho/triton-windows/releases/tag/v3.1.0-windows.post5)からダウンロードしてインストールします。 + +2. Microsoft Visual Studio 2022かBuild Tools for Visual Studio 2022を、C++のビルドができるよう設定し、インストールします。(上のRedditの投稿を参照してください)。 + +3. 任意のフォルダにSageAttentionのリポジトリをクローンします。 + ```shell + git clone https://github.com/thu-ml/SageAttention.git + ``` + +4. スタートメニューから Visual Studio 2022 内の `x64 Native Tools Command Prompt for VS 2022` を選択してコマンドプロンプトを開きます。 + +5. venvを有効にし、SageAttentionのフォルダに移動して以下のコマンドを実行します。DISTUTILSが設定されていない、のようなエラーが出た場合は `set DISTUTILS_USE_SDK=1`としてから再度実行してください。 + ```shell + python setup.py install + ``` + +以上でSageAttentionのインストールが完了です。 + +### PyTorchのバージョンについて + +`--attn_mode`に`torch`を指定する場合、2.5.1以降のPyTorchを使用してください(それより前のバージョンでは生成される動画が真っ黒になるようです)。 + +古いバージョンを使う場合、xformersやSageAttentionを使用してください。 + +## 免責事項 + +このリポジトリは非公式であり、サポートされているアーキテクチャの公式リポジトリとは関係ありません。また、このリポジトリは開発中で、実験的なものです。テストおよびフィードバックを歓迎しますが、以下の点にご注意ください: + +- 実際の稼働環境での動作を意図したものではありません +- 機能やAPIは予告なく変更されることがあります +- いくつもの機能が未検証です +- 動画学習機能はまだ開発中です + +問題やバグについては、以下の情報とともにIssueを作成してください: + +- 問題の詳細な説明 +- 再現手順 +- 環境の詳細(OS、GPU、VRAM、Pythonバージョンなど) +- 関連するエラーメッセージやログ + +## コントリビューションについて + +コントリビューションを歓迎します。 [CONTRIBUTING.md](./CONTRIBUTING.md)および[CONTRIBUTING.ja.md](./CONTRIBUTING.ja.md)をご覧ください。 + +## ライセンス + +`hunyuan_model`ディレクトリ以下のコードは、[HunyuanVideo](https://github.com/Tencent/HunyuanVideo)のコードを一部改変して使用しているため、そちらのライセンスに従います。 + +`wan`ディレクトリ以下のコードは、[Wan2.1](https://github.com/Wan-Video/Wan2.1)のコードを一部改変して使用しています。ライセンスはApache License 2.0です。 + +`frame_pack`ディレクトリ以下のコードは、[frame_pack](https://github.com/lllyasviel/FramePack)のコードを一部改変して使用しています。ライセンスはApache License 2.0です。 + +他のコードはApache License 2.0に従います。一部Diffusersのコードをコピー、改変して使用しています。 diff --git a/VRGDG_Musubi-tuner/README.md b/VRGDG_Musubi-tuner/README.md new file mode 100644 index 0000000000000000000000000000000000000000..cd80b4cfef00a82b2725873742faeb2c68b942df --- /dev/null +++ b/VRGDG_Musubi-tuner/README.md @@ -0,0 +1,326 @@ +# Musubi Tuner + +[English](./README.md) | [日本語](./README.ja.md) + +## Table of Contents + +
+Click to expand + +- [Musubi Tuner](#musubi-tuner) + - [Table of Contents](#table-of-contents) + - [Introduction](#introduction) + - [Sponsors](#sponsors) + - [Support the Project](#support-the-project) + - [Recent Updates](#recent-updates) + - [Releases](#releases) + - [For Developers Using AI Coding Agents](#for-developers-using-ai-coding-agents) + - [Overview](#overview) + - [Hardware Requirements](#hardware-requirements) + - [Features](#features) + - [Documentation](#documentation) + - [Installation](#installation) + - [pip based installation](#pip-based-installation) + - [uv based installation](#uv-based-installation-experimental) + - [Linux/MacOS](#linuxmacos) + - [Windows](#windows) + - [Model Download](#model-download) + - [Usage](#usage) + - [Dataset Configuration](#dataset-configuration) + - [Pre-caching and Training](#pre-caching-and-training) + - [Configuration of Accelerate](#configuration-of-accelerate) + - [Training and Inference](#training-and-inference) + - [Miscellaneous](#miscellaneous) + - [SageAttention Installation](#sageattention-installation) + - [PyTorch version](#pytorch-version) + - [Disclaimer](#disclaimer) + - [Contributing](#contributing) + - [License](#license) + +
+ +## Introduction + +This repository provides scripts for training LoRA (Low-Rank Adaptation) models with HunyuanVideo, Wan2.1/2.2, FramePack, FLUX.1 Kontext, FLUX.2 dev/klein, Qwen-Image, Z-Image, and [LTX-2](./docs/ltx_2.md) architectures. + +This repository is unofficial and not affiliated with the official repositories of these architectures. + +*This repository is under development.* + +### Sponsors + +We are grateful to the following companies for their generous sponsorship: + + + AiHUB Inc. + + +### Support the Project + +If you find this project helpful, please consider supporting its development via [GitHub Sponsors](https://github.com/sponsors/kohya-ss/). Your support is greatly appreciated! + +### Recent Updates + +GitHub Discussions Enabled: We've enabled GitHub Discussions for community Q&A, knowledge sharing, and technical information exchange. Please use Issues for bug reports and feature requests, and Discussions for questions and sharing experiences. [Join the conversation →](https://github.com/kohya-ss/musubi-tuner/discussions) + +- February 15, 2026 + - Added support for LoHa/LoKr training. See [PR #900](https://github.com/kohya-ss/musubi-tuner/pull/900) + - Implemented based on the LoHa/LoKr algorithms from LyCORIS. Special thanks to KohakuBlueleaf from the LyCORIS project. + - Please refer to the [documentation](./docs/loha_lokr.md) for details. + - Added `--block_swap_optimizer_patch_params` option to enable the use of some optimizers when using `blocks_to_swap` in Z-Image fine-tuning. See [PR #899](https://github.com/kohya-ss/musubi-tuner/pull/899) + - Please refer to the [documentation](./docs/zimage.md#finetuning) for details. + +- January 29, 2026 + - With the release of Z-Image-Base, we have verified that both LoRA and finetuning work correctly. + - Updated the [related documentation](./docs/zimage.md) for Z-Image. + - Fixed an issue where sample image generation did not work correctly in LoRA training and finetuning of Z-Image. See [PR #861](https://github.com/kohya-ss/musubi-tuner/pull/861). + +- January 24, 2026 + - Fixed an issue where LoRA training for FLUX.2 [klein] did not work. Also made various bug fixes and feature additions related to FLUX.2. See [PR #858](https://github.com/kohya-ss/musubi-tuner/pull/858). + - The `--model_version` specification has changed from `flux.2-dev` or `flux.2-klein-4b` to `dev` or `klein-4b`, etc. + - fp8 optimization and other features also work. Please refer to the [documentation](./docs/flux_2.md) for details. + - Since klein 9B, dev models, and training with multiple control images have not been sufficiently tested, please report any issues via Issue. + +- January 21, 2026 + - Added support for LoRA training of FLUX.2 [dev]/[klein]. See [PR #841](https://github.com/kohya-ss/musubi-tuner/pull/841). Many thanks to christopher5106 from https://www.scenario.com for this contribution. + - Please refer to the [documentation](./docs/flux_2.md) for details. + +- January 17, 2026 + - Changed to use `convert_lora.py` for converting Z-Image LoRA for ComfyUI to improve compatibility. See [PR #851](https://github.com/kohya-ss/musubi-tuner/pull/851). + - The previous `convert_z_image_lora_to_comfy.py` can still be used, but the converted weights may not work correctly with nunchaku. + - Please refer to the [documentation](./docs/zimage.md#converting-lora-weights-to-diffusers-format-for-comfyui--lora重みをcomfyuiで使用可能なdiffusers形式に変換する) for details. + - Many thanks to fai-9 for providing the solution in [Issue #847](https://github.com/kohya-ss/musubi-tuner/issues/847). + - Added `--remove_first_image_from_target` option for LoRA training of Qwen-Image-Layered. See [PR #852](https://github.com/kohya-ss/musubi-tuner/pull/852). + - Please refer to the [documentation](./docs/qwen_image.md#lora-training--lora学習) for details. + +- January 11, 2026 + - Added support for LoRA training of Qwen-Image-Layered. See [PR #816](https://github.com/kohya-ss/musubi-tuner/pull/816). + - Please refer to the [documentation](./docs/qwen_image.md) for details. + - In the caching, training, and inference scripts, specify `--model_version` option as `layered`. + +### Releases + +We are grateful to everyone who has been contributing to the Musubi Tuner ecosystem through documentation and third-party tools. To support these valuable contributions, we recommend working with our [releases](https://github.com/kohya-ss/musubi-tuner/releases) as stable reference points, as this project is under active development and breaking changes may occur. + +You can find the latest release and version history in our [releases page](https://github.com/kohya-ss/musubi-tuner/releases). + +### For Developers Using AI Coding Agents + +This repository provides recommended instructions to help AI agents like Claude and Gemini understand our project context and coding standards. + +To use them, you need to opt-in by creating your own configuration file in the project root. + +**Quick Setup:** + +1. Create a `CLAUDE.md`, `GEMINI.md`, and/or `AGENTS.md` file in the project root. +2. Add the following line to your `CLAUDE.md` to import the repository's recommended prompt (currently they are the almost same): + + ```markdown + @./.ai/claude.prompt.md + ``` + + or for Gemini: + + ```markdown + @./.ai/gemini.prompt.md + ``` + + You may be also import the prompt depending on the agent you are using with the custom prompt file such as `AGENTS.md`. + +3. You can now add your own personal instructions below the import line (e.g., `Always include a short summary of the change before diving into details.`). + +This approach ensures that you have full control over the instructions given to your agent while benefiting from the shared project context. Your `CLAUDE.md`, `GEMINI.md` and `AGENTS.md` (as well as Claude's `.mcp.json`) are already listed in `.gitignore`, so they won't be committed to the repository. + +## Overview + +### Hardware Requirements + +- VRAM: 12GB or more recommended for image training, 24GB or more for video training + - *Actual requirements depend on resolution and training settings.* For 12GB, use a resolution of 960x544 or lower and use memory-saving options such as `--blocks_to_swap`, `--fp8_llm`, etc. +- Main Memory: 64GB or more recommended, 32GB + swap may work + +### Features + +- Memory-efficient implementation +- Windows compatibility confirmed (Linux compatibility confirmed by community) +- Multi-GPU training (using [Accelerate](https://huggingface.co/docs/accelerate/index)), documentation will be added later + +### Documentation + +For detailed information on specific architectures, configurations, and advanced features, please refer to the documentation below. + +**Architecture-specific:** +- [HunyuanVideo](./docs/hunyuan_video.md) +- [Wan2.1/2.2](./docs/wan.md) +- [Wan2.1/2.2 (Single Frame)](./docs/wan_1f.md) +- [FramePack](./docs/framepack.md) +- [FramePack (Single Frame)](./docs/framepack_1f.md) +- [FLUX.1 Kontext](./docs/flux_kontext.md) +- [Qwen-Image](./docs/qwen_image.md) +- [Z-Image](./docs/zimage.md) +- [HunyuanVideo 1.5](./docs/hunyuan_video_1_5.md) +- [Kandinsky 5](./docs/kandinsky5.md) +- [LTX-2](./docs/ltx_2.md) +- [FLUX.2](./docs/flux_2.md) + +**Common Configuration & Usage:** +- [Dataset Configuration](./docs/dataset_config.md) +- [Advanced Configuration](./docs/advanced_config.md) +- [Sampling during Training](./docs/sampling_during_training.md) +- [Tools and Utilities](./docs/tools.md) +- [Using torch.compile](./docs/torch_compile.md) + +## Installation + +### pip based installation + +Python 3.10 or later is required (verified with 3.10). + +Create a virtual environment and install PyTorch and torchvision matching your CUDA version. + +PyTorch 2.5.1 or later is required (see [note](#PyTorch-version)). + +```bash +pip install torch torchvision --index-url https://download.pytorch.org/whl/cu124 +``` + +Install the required dependencies using the following command. + +```bash +pip install -e . +``` + +Optionally, you can use FlashAttention and SageAttention (**for inference only**; see [SageAttention Installation](#sageattention-installation) for installation instructions). + +Optional dependencies for additional features: +- `ascii-magic`: Used for dataset verification +- `matplotlib`: Used for timestep visualization +- `tensorboard`: Used for logging training progress +- `prompt-toolkit`: Used for interactive prompt editing in Wan2.1 and FramePack inference scripts. If installed, it will be automatically used in interactive mode. Especially useful in Linux environments for easier prompt editing. + +```bash +pip install ascii-magic matplotlib tensorboard prompt-toolkit +``` + +### uv based installation (experimental) + +You can also install using uv, but installation with uv is experimental. Feedback is welcome. + +1. Install uv (if not already present on your OS). + +#### Linux/MacOS + +```sh +curl -LsSf https://astral.sh/uv/install.sh | sh +``` + +Follow the instructions to add the uv path manually until you restart your session... + +#### Windows + +```powershell +powershell -c "irm https://astral.sh/uv/install.ps1 | iex" +``` + +Follow the instructions to add the uv path manually until you reboot your system... or just reboot your system at this point. + +## Model Download + +Model download procedures vary by architecture. Please refer to the architecture-specific documents in the [Documentation](#documentation) section for instructions. + +## Usage + + +### Dataset Configuration + +Please refer to [here](./docs/dataset_config.md). + +### Pre-caching + +Pre-caching procedures vary by architecture. Please refer to the architecture-specific documents in the [Documentation](#documentation) section for instructions. + +### Configuration of Accelerate + +Run `accelerate config` to configure Accelerate. Choose appropriate values for each question based on your environment (either input values directly or use arrow keys and enter to select; uppercase is default, so if the default value is fine, just press enter without inputting anything). For training with a single GPU, answer the questions as follows: + +```txt +- In which compute environment are you running?: This machine +- Which type of machine are you using?: No distributed training +- Do you want to run your training on CPU only (even if a GPU / Apple Silicon / Ascend NPU device is available)?[yes/NO]: NO +- Do you wish to optimize your script with torch dynamo?[yes/NO]: NO +- Do you want to use DeepSpeed? [yes/NO]: NO +- What GPU(s) (by id) should be used for training on this machine as a comma-seperated list? [all]: all +- Would you like to enable numa efficiency? (Currently only supported on NVIDIA hardware). [yes/NO]: NO +- Do you wish to use mixed precision?: bf16 +``` + +*Note*: In some cases, you may encounter the error `ValueError: fp16 mixed precision requires a GPU`. If this happens, answer "0" to the sixth question (`What GPU(s) (by id) should be used for training on this machine as a comma-separated list? [all]:`). This means that only the first GPU (id `0`) will be used. + +### Training and Inference + +Training and inference procedures vary significantly by architecture. Please refer to the architecture-specific documents in the [Documentation](#documentation) section and the various configuration documents for detailed instructions. + +## Miscellaneous + +### SageAttention Installation + +sdbsd has provided a Windows-compatible SageAttention implementation and pre-built wheels here: https://github.com/sdbds/SageAttention-for-windows. After installing triton, if your Python, PyTorch, and CUDA versions match, you can download and install the pre-built wheel from the [Releases](https://github.com/sdbds/SageAttention-for-windows/releases) page. Thanks to sdbsd for this contribution. + +For reference, the build and installation instructions are as follows. You may need to update Microsoft Visual C++ Redistributable to the latest version. + +1. Download and install triton 3.1.0 wheel matching your Python version from [here](https://github.com/woct0rdho/triton-windows/releases/tag/v3.1.0-windows.post5). + +2. Install Microsoft Visual Studio 2022 or Build Tools for Visual Studio 2022, configured for C++ builds. + +3. Clone the SageAttention repository in your preferred directory: + ```shell + git clone https://github.com/thu-ml/SageAttention.git + ``` + +4. Open `x64 Native Tools Command Prompt for VS 2022` from the Start menu under Visual Studio 2022. + +5. Activate your venv, navigate to the SageAttention folder, and run the following command. If you get a DISTUTILS not configured error, set `set DISTUTILS_USE_SDK=1` and try again: + ```shell + python setup.py install + ``` + +This completes the SageAttention installation. + +### PyTorch version + +If you specify `torch` for `--attn_mode`, use PyTorch 2.5.1 or later (earlier versions may result in black videos). + +If you use an earlier version, use xformers or SageAttention. + +## Disclaimer + +This repository is unofficial and not affiliated with the official repositories of the supported architectures. + +This repository is experimental and under active development. While we welcome community usage and feedback, please note: + +- This is not intended for production use +- Features and APIs may change without notice +- Some functionalities are still experimental and may not work as expected +- Video training features are still under development + +If you encounter any issues or bugs, please create an Issue in this repository with: +- A detailed description of the problem +- Steps to reproduce +- Your environment details (OS, GPU, VRAM, Python version, etc.) +- Any relevant error messages or logs + +## Contributing + +We welcome contributions! Please see [CONTRIBUTING.md](./CONTRIBUTING.md) for details. + +## License + +Code under the `hunyuan_model` directory is modified from [HunyuanVideo](https://github.com/Tencent/HunyuanVideo) and follows their license. + +Code under the `hunyuan_video_1_5` directory is modified from [HunyuanVideo 1.5](https://github.com/Tencent-Hunyuan/HunyuanVideo-1.5) and follows their license. + +Code under the `wan` directory is modified from [Wan2.1](https://github.com/Wan-Video/Wan2.1). The license is under the Apache License 2.0. + +Code under the `frame_pack` directory is modified from [FramePack](https://github.com/lllyasviel/FramePack). The license is under the Apache License 2.0. + +Other code is under the Apache License 2.0. Some code is copied and modified from Diffusers. \ No newline at end of file diff --git a/VRGDG_Musubi-tuner/cache_latents.py b/VRGDG_Musubi-tuner/cache_latents.py new file mode 100644 index 0000000000000000000000000000000000000000..dc2cab0eafa81412242bc6ad16f3c08ab3e6aa17 --- /dev/null +++ b/VRGDG_Musubi-tuner/cache_latents.py @@ -0,0 +1,4 @@ +from musubi_tuner.cache_latents import main + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/cache_text_encoder_outputs.py b/VRGDG_Musubi-tuner/cache_text_encoder_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..c7be3af2173913a2fc5d4a40cd34a223f9ee066f --- /dev/null +++ b/VRGDG_Musubi-tuner/cache_text_encoder_outputs.py @@ -0,0 +1,4 @@ +from musubi_tuner.cache_text_encoder_outputs import main + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/caption_images_by_qwen_vl.py b/VRGDG_Musubi-tuner/caption_images_by_qwen_vl.py new file mode 100644 index 0000000000000000000000000000000000000000..5f307b98e5cebeba8ac1d908345e156bcad1e7f9 --- /dev/null +++ b/VRGDG_Musubi-tuner/caption_images_by_qwen_vl.py @@ -0,0 +1,4 @@ +from musubi_tuner.caption_images_by_qwen_vl import main + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/convert_lora.py b/VRGDG_Musubi-tuner/convert_lora.py new file mode 100644 index 0000000000000000000000000000000000000000..8280a39d527fbb3ad51d91db9514bdbfc64088a3 --- /dev/null +++ b/VRGDG_Musubi-tuner/convert_lora.py @@ -0,0 +1,4 @@ +from musubi_tuner.convert_lora import main + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/docs/advanced_config.md b/VRGDG_Musubi-tuner/docs/advanced_config.md new file mode 100644 index 0000000000000000000000000000000000000000..a94f008dfb9a8bb6fc0b5e20fb51c64341edb18e --- /dev/null +++ b/VRGDG_Musubi-tuner/docs/advanced_config.md @@ -0,0 +1,831 @@ +> 📝 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" +``` + +
\ No newline at end of file diff --git a/VRGDG_Musubi-tuner/docs/betas_for_sigma_rel.png b/VRGDG_Musubi-tuner/docs/betas_for_sigma_rel.png new file mode 100644 index 0000000000000000000000000000000000000000..ca96d0c7f48d22529de74769cf52e6e91a59c889 --- /dev/null +++ b/VRGDG_Musubi-tuner/docs/betas_for_sigma_rel.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:77ec2f19a0ef7e6a677a30b8530b05eeeeb0fa9c33df723c38ede3532c478d21 +size 66031 diff --git a/VRGDG_Musubi-tuner/docs/dataset_config.md b/VRGDG_Musubi-tuner/docs/dataset_config.md new file mode 100644 index 0000000000000000000000000000000000000000..cdc72d519bb3de2c3e684b574e5dd331283d7fcc --- /dev/null +++ b/VRGDG_Musubi-tuner/docs/dataset_config.md @@ -0,0 +1,724 @@ +> 📝 Click on the language section to expand / 言語をクリックして展開 + +## Dataset Configuration + +Please create a TOML file for dataset configuration. + +Image and video datasets are supported. The configuration file can include multiple datasets, either image or video datasets, with caption text files or metadata JSONL files. + +The cache directory must be different for each dataset. + +Each video is extracted frame by frame without additional processing and used for training. It is recommended to use videos with a frame rate of 24fps for HunyuanVideo, 16fps for Wan2.1 and 30fps for FramePack. You can check the videos that will be trained using `--debug_mode video` when caching latent (see [here](/README.md#latent-caching)). +
+日本語 + +データセットの設定を行うためのTOMLファイルを作成してください。 + +画像データセットと動画データセットがサポートされています。設定ファイルには、画像または動画データセットを複数含めることができます。キャプションテキストファイルまたはメタデータJSONLファイルを使用できます。 + +キャッシュディレクトリは、各データセットごとに異なるディレクトリである必要があります。 + +動画は追加のプロセスなしでフレームごとに抽出され、学習に用いられます。そのため、HunyuanVideoは24fps、Wan2.1は16fps、FramePackは30fpsのフレームレートの動画を使用することをお勧めします。latentキャッシュ時の`--debug_mode video`を使用すると、学習される動画を確認できます([こちら](/README.ja.md#latentの事前キャッシュ)を参照)。 +
+ +### Sample for Image Dataset with Caption Text Files + +```toml +# resolution, caption_extension, batch_size, num_repeats, enable_bucket, bucket_no_upscale should be set in either general or datasets +# otherwise, the default values will be used for each item + +# general configurations +[general] +resolution = [960, 544] +caption_extension = ".txt" +batch_size = 1 +enable_bucket = true +bucket_no_upscale = false + +[[datasets]] +image_directory = "/path/to/image_dir" +cache_directory = "/path/to/cache_directory" +num_repeats = 1 # optional, default is 1. Number of times to repeat the dataset. Useful to balance the multiple datasets with different sizes. +# multiple_target = true # optional, default is false. Set to true for Qwen-Image-Layered training. + +# other datasets can be added here. each dataset can have different configurations +``` + +`image_directory` is the directory containing images. The captions are stored in text files with the same filename as the image, but with the extension specified by `caption_extension` (for example, `image1.jpg` and `image1.txt`). + +`cache_directory` is optional, default is None to use the same directory as the image directory. However, we recommend to set the cache directory to avoid accidental sharing of the cache files between different datasets. + +`num_repeats` is also available. It is optional, default is 1 (no repeat). It repeats the images (or videos) that many times to expand the dataset. For example, if `num_repeats = 2` and there are 20 images in the dataset, each image will be duplicated twice (with the same caption) to have a total of 40 images. It is useful to balance the multiple datasets with different sizes. + +For Qwen-Image-Layered training, set `multiple_target = true`. Also, in the `image_directory`, for each "image to be trained + segmentation (layer) results" combination, store the following (if `caption_extension` is `.txt`): + +|Item|Example|Note| +|---|---|---| +|Caption file|`image1.txt`| | +|Image to be trained (image to be layered)|`image1.png`| | +|Segmentation (layer) result images|`image1_1.png`, `image1_2.png`, ...|Alpha channel required| + +The next combination would be stored as `/path/to/layer_images/image2.txt` for caption, and `/path/to/layer_images/image2.png`, `/path/to/layer_images/image2_0.png`, `/path/to/layer_images/image2_1.png` for images. + +
+日本語 + +`image_directory`は画像を含むディレクトリのパスです。キャプションは、画像と同じファイル名で、`caption_extension`で指定した拡張子のテキストファイルに格納してください(例:`image1.jpg`と`image1.txt`)。 + +`cache_directory` はオプションです。デフォルトは画像ディレクトリと同じディレクトリに設定されます。ただし、異なるデータセット間でキャッシュファイルが共有されるのを防ぐために、明示的に別のキャッシュディレクトリを設定することをお勧めします。 + +`num_repeats` はオプションで、デフォルトは 1 です(繰り返しなし)。画像(や動画)を、その回数だけ単純に繰り返してデータセットを拡張します。たとえば`num_repeats = 2`としたとき、画像20枚のデータセットなら、各画像が2枚ずつ(同一のキャプションで)計40枚存在した場合と同じになります。異なるデータ数のデータセット間でバランスを取るために使用可能です。 + +resolution, caption_extension, batch_size, num_repeats, enable_bucket, bucket_no_upscale は general または datasets のどちらかに設定してください。省略時は各項目のデフォルト値が使用されます。 + +`[[datasets]]`以下を追加することで、他のデータセットを追加できます。各データセットには異なる設定を持てます。 + +Qwen-Image-Layeredの学習の場合、`multiple_target = true`を設定してください。また、`image_directory`内に、それぞれの「学習する画像+分割結果」組み合わせごとに、以下を格納してください(`caption_extension`が`.txt`の場合)。 + +|項目|例|備考| +|---|---|---| +|キャプションファイル|`image1.txt`| | +|学習する画像(分割対象の画像)|`image1.png`| | +|分割結果のレイヤー画像群|`image1_1.png`, `image1_2.png`, ...|アルファチャンネル必須| + +次の組み合わせは、`/path/to/layer_images/image2.txt`に対して、`/path/to/layer_images/image2.png`, `/path/to/layer_images/image2_0.png`, `/path/to/layer_images/image2_1.png`のように格納します。 + +
+ +### Sample for Image Dataset with Metadata JSONL File + +```toml +# resolution, batch_size, num_repeats, enable_bucket, bucket_no_upscale should be set in either general or datasets +# caption_extension is not required for metadata jsonl file +# cache_directory is required for each dataset with metadata jsonl file + +# general configurations +[general] +resolution = [960, 544] +batch_size = 1 +enable_bucket = true +bucket_no_upscale = false + +[[datasets]] +image_jsonl_file = "/path/to/metadata.jsonl" +cache_directory = "/path/to/cache_directory" # required for metadata jsonl file +num_repeats = 1 # optional, default is 1. Same as above. +# multiple_target = true # optional, default is false. Set to true for Qwen-Image-Layered training. + +# other datasets can be added here. each dataset can have different configurations +``` + +JSONL file format for metadata: + +```json +{"image_path": "/path/to/image1.jpg", "caption": "A caption for image1"} +{"image_path": "/path/to/image2.jpg", "caption": "A caption for image2"} +``` + +For Qwen-Image-Layered training, set `multiple_target = true`. Also, in the metadata JSONL file, for each "image to be trained + segmentation (layer) results" combination, specify the image paths with numbered attributes like `image_path_0`, `image_path_1`, etc. + +```json +{"image_path_0": "/path/to/image1_base.png", "image_path_1": "/path/to/image1_layer1.png", "image_path_2": "/path/to/image1_layer2.png", "caption": "A caption for image1"} +{"image_path_0": "/path/to/image2_base.png", "image_path_1": "/path/to/image2_layer1.png", "image_path_2": "/path/to/image2_layer2.png", "caption": "A caption for image2"} +``` + +
+日本語 + +resolution, batch_size, num_repeats, enable_bucket, bucket_no_upscale は general または datasets のどちらかに設定してください。省略時は各項目のデフォルト値が使用されます。 + +metadata jsonl ファイルを使用する場合、caption_extension は必要ありません。また、cache_directory は必須です。 + +キャプションによるデータセットと同様に、複数のデータセットを追加できます。各データセットには異なる設定を持てます。 + +Qwen-Image-Layeredの学習の場合、`multiple_target = true`を設定してください。また、metadata jsonl ファイル内で、各画像に対して複数のターゲット画像を指定する場合は、`image_path_0`, `image_path_1`のように数字を付与してください。 + +
+ + +### Sample for Video Dataset with Caption Text Files + +```toml +# Common parameters (resolution, caption_extension, batch_size, num_repeats, enable_bucket, bucket_no_upscale) +# can be set in either general or datasets sections +# Video-specific parameters (target_frames, frame_extraction, frame_stride, frame_sample, max_frames, source_fps) +# must be set in each datasets section + +# general configurations +[general] +resolution = [960, 544] +caption_extension = ".txt" +batch_size = 1 +enable_bucket = true +bucket_no_upscale = false + +[[datasets]] +video_directory = "/path/to/video_dir" +cache_directory = "/path/to/cache_directory" # recommended to set cache directory +target_frames = [1, 25, 45] +frame_extraction = "head" +source_fps = 30.0 # optional, source fps for videos in the directory, decimal number + +[[datasets]] +video_directory = "/path/to/video_dir2" +cache_directory = "/path/to/cache_directory2" # recommended to set cache directory +frame_extraction = "full" +max_frames = 45 + +# other datasets can be added here. each dataset can have different configurations +``` + +`video_directory` is the directory containing videos. The captions are stored in text files with the same filename as the video, but with the extension specified by `caption_extension` (for example, `video1.mp4` and `video1.txt`). + +__In HunyuanVideo and Wan2.1, the number of `target_frames` must be "N\*4+1" (N=0,1,2,...).__ Otherwise, it will be truncated to the nearest "N*4+1". + +In FramePack, it is recommended to set `frame_extraction` to `full` and `max_frames` to a sufficiently large value, as it can handle longer videos. However, if the video is too long, an Out of Memory error may occur during VAE encoding. The videos in FramePack are trimmed to "N * latent_window_size * 4 + 1" frames (for example, 37, 73, 109... if `latent_window_size` is 9). + +If the `source_fps` is specified, the videos in the directory are considered to be at this frame rate, and some frames will be skipped to match the model's frame rate (24 for HunyuanVideo and 16 for Wan2.1). __The value must be a decimal number, for example, `30.0` instead of `30`.__ The skipping is done automatically and does not consider the content of the images. Please check if the converted data is correct using `--debug_mode video`. + +If `source_fps` is not specified (default), all frames of the video will be used regardless of the video's frame rate. + +
+日本語 + +共通パラメータ(resolution, caption_extension, batch_size, num_repeats, enable_bucket, bucket_no_upscale)は、generalまたはdatasetsのいずれかに設定できます。 +動画固有のパラメータ(target_frames, frame_extraction, frame_stride, frame_sample, max_frames, source_fps)は、各datasetsセクションに設定する必要があります。 + +`video_directory`は動画を含むディレクトリのパスです。キャプションは、動画と同じファイル名で、`caption_extension`で指定した拡張子のテキストファイルに格納してください(例:`video1.mp4`と`video1.txt`)。 + +__HunyuanVideoおよびWan2.1では、target_framesの数値は「N\*4+1」である必要があります。__ これ以外の値の場合は、最も近いN\*4+1の値に切り捨てられます。 + +FramePackでも同様ですが、FramePackでは動画が長くても学習可能なため、 `frame_extraction`に`full` を指定し、`max_frames`を十分に大きな値に設定することをお勧めします。ただし、あまりにも長すぎるとVAEのencodeでOut of Memoryエラーが発生する可能性があります。FramePackの動画は、「N * latent_window_size * 4 + 1」フレームにトリミングされます(latent_window_sizeが9の場合、37、73、109……)。 + +`source_fps`を指定した場合、ディレクトリ内の動画をこのフレームレートとみなして、モデルのフレームレートにあうようにいくつかのフレームをスキップします(HunyuanVideoは24、Wan2.1は16)。__小数点を含む数値で指定してください。__ 例:`30`ではなく`30.0`。スキップは機械的に行われ、画像の内容は考慮しません。変換後のデータが正しいか、`--debug_mode video`で確認してください。 + +`source_fps`を指定しない場合、動画のフレームは(動画自体のフレームレートに関係なく)すべて使用されます。 + +他の注意事項は画像データセットと同様です。 +
+ +### Sample for Video Dataset with Metadata JSONL File + +```toml +# Common parameters (resolution, caption_extension, batch_size, num_repeats, enable_bucket, bucket_no_upscale) +# can be set in either general or datasets sections +# Video-specific parameters (target_frames, frame_extraction, frame_stride, frame_sample, max_frames, source_fps) +# must be set in each datasets section + +# caption_extension is not required for metadata jsonl file +# cache_directory is required for each dataset with metadata jsonl file + +# general configurations +[general] +resolution = [960, 544] +batch_size = 1 +enable_bucket = true +bucket_no_upscale = false + +[[datasets]] +video_jsonl_file = "/path/to/metadata.jsonl" +target_frames = [1, 25, 45] +frame_extraction = "head" +cache_directory = "/path/to/cache_directory_head" +source_fps = 30.0 # optional, source fps for videos in the jsonl file +# same metadata jsonl file can be used for multiple datasets +[[datasets]] +video_jsonl_file = "/path/to/metadata.jsonl" +target_frames = [1] +frame_stride = 10 +cache_directory = "/path/to/cache_directory_stride" + +# other datasets can be added here. each dataset can have different configurations +``` + +JSONL file format for metadata: + +```json +{"video_path": "/path/to/video1.mp4", "caption": "A caption for video1"} +{"video_path": "/path/to/video2.mp4", "caption": "A caption for video2"} +``` + +`video_path` can be a directory containing multiple images. + +
+日本語 +metadata jsonl ファイルを使用する場合、caption_extension は必要ありません。また、cache_directory は必須です。 + +`video_path`は、複数の画像を含むディレクトリのパスでも構いません。 + +他の注意事項は今までのデータセットと同様です。 +
+ +### frame_extraction Options + +- `head`: Extract the first N frames from the video. +- `chunk`: Extract frames by splitting the video into chunks of N frames. +- `slide`: Extract frames from the video with a stride of `frame_stride`. +- `uniform`: Extract `frame_sample` samples uniformly from the video. +- `full`: Extract all frames from the video. + +In the case of `full`, the entire video is used, but it is trimmed to "N*4+1" frames. It is also trimmed to the `max_frames` if it exceeds that value. To avoid Out of Memory errors, please set `max_frames`. + +The frame extraction methods other than `full` are recommended when the video contains repeated actions. `full` is recommended when each video represents a single complete motion. + +For example, consider a video with 40 frames. The following diagrams illustrate each extraction: + +
+日本語 + +- `head`: 動画から最初のNフレームを抽出します。 +- `chunk`: 動画をNフレームずつに分割してフレームを抽出します。 +- `slide`: `frame_stride`に指定したフレームごとに動画からNフレームを抽出します。 +- `uniform`: 動画から一定間隔で、`frame_sample`個のNフレームを抽出します。 +- `full`: 動画から全てのフレームを抽出します。 + +`full`の場合、各動画の全体を用いますが、「N*4+1」のフレーム数にトリミングされます。また`max_frames`を超える場合もその値にトリミングされます。Out of Memoryエラーを避けるために、`max_frames`を設定してください。 + +`full`以外の抽出方法は、動画が特定の動作を繰り返している場合にお勧めします。`full`はそれぞれの動画がひとつの完結したモーションの場合にお勧めします。 + +例えば、40フレームの動画を例とした抽出について、以下の図で説明します。 +
+ +``` +Original Video, 40 frames: x = frame, o = no frame +oooooooooooooooooooooooooooooooooooooooo + +head, target_frames = [1, 13, 25] -> extract head frames: +xooooooooooooooooooooooooooooooooooooooo +xxxxxxxxxxxxxooooooooooooooooooooooooooo +xxxxxxxxxxxxxxxxxxxxxxxxxooooooooooooooo + +chunk, target_frames = [13, 25] -> extract frames by splitting into chunks, into 13 and 25 frames: +xxxxxxxxxxxxxooooooooooooooooooooooooooo +oooooooooooooxxxxxxxxxxxxxoooooooooooooo +ooooooooooooooooooooooooooxxxxxxxxxxxxxo +xxxxxxxxxxxxxxxxxxxxxxxxxooooooooooooooo + +NOTE: Please do not include 1 in target_frames if you are using the frame_extraction "chunk". It will make the all frames to be extracted. +注: frame_extraction "chunk" を使用する場合、target_frames に 1 を含めないでください。全てのフレームが抽出されてしまいます。 + +slide, target_frames = [1, 13, 25], frame_stride = 10 -> extract N frames with a stride of 10: +xooooooooooooooooooooooooooooooooooooooo +ooooooooooxooooooooooooooooooooooooooooo +ooooooooooooooooooooxooooooooooooooooooo +ooooooooooooooooooooooooooooooxooooooooo +xxxxxxxxxxxxxooooooooooooooooooooooooooo +ooooooooooxxxxxxxxxxxxxooooooooooooooooo +ooooooooooooooooooooxxxxxxxxxxxxxooooooo +xxxxxxxxxxxxxxxxxxxxxxxxxooooooooooooooo +ooooooooooxxxxxxxxxxxxxxxxxxxxxxxxxooooo + +uniform, target_frames =[1, 13, 25], frame_sample = 4 -> extract `frame_sample` samples uniformly, N frames each: +xooooooooooooooooooooooooooooooooooooooo +oooooooooooooxoooooooooooooooooooooooooo +oooooooooooooooooooooooooxoooooooooooooo +ooooooooooooooooooooooooooooooooooooooox +xxxxxxxxxxxxxooooooooooooooooooooooooooo +oooooooooxxxxxxxxxxxxxoooooooooooooooooo +ooooooooooooooooooxxxxxxxxxxxxxooooooooo +oooooooooooooooooooooooooooxxxxxxxxxxxxx +xxxxxxxxxxxxxxxxxxxxxxxxxooooooooooooooo +oooooxxxxxxxxxxxxxxxxxxxxxxxxxoooooooooo +ooooooooooxxxxxxxxxxxxxxxxxxxxxxxxxooooo +oooooooooooooooxxxxxxxxxxxxxxxxxxxxxxxxx + +Three Original Videos, 20, 25, 35 frames: x = frame, o = no frame + +full, max_frames = 31 -> extract all frames (trimmed to the maximum length): +video1: xxxxxxxxxxxxxxxxx (trimmed to 17 frames) +video2: xxxxxxxxxxxxxxxxxxxxxxxxx (25 frames) +video3: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx (trimmed to 31 frames) +``` + +### Sample for Image Dataset with Control Images + +The dataset with control images. This is used for the one frame training for FramePack, or for FLUX.1 Kontext, FLUX.2 and Qwen-Image-Edit training. + +The dataset configuration with caption text files is similar to the image dataset, but with an additional `control_directory` parameter. + +The control images are used from the `control_directory` with the same filename (or different extension) as the image, for example, `image_dir/image1.jpg` and `control_dir/image1.png`. The images in `image_directory` should be the target images (the images to be generated during inference, the changed images). The `control_directory` should contain the starting images for inference. The captions should be stored in `image_directory`. + +If multiple control images are specified, the filenames of the control images should be numbered (excluding the extension). For example, specify `image_dir/image1.jpg` and `control_dir/image1_0.png`, `control_dir/image1_1.png`. You can also specify the numbers with four digits, such as `image1_0000.png`, `image1_0001.png`. + +The metadata JSONL file format is the same as the image dataset, but with an additional `control_path` parameter. + +```json +{"image_path": "/path/to/image1.jpg", "control_path": "/path/to/control1.png", "caption": "A caption for image1"} +{"image_path": "/path/to/image2.jpg", "control_path": "/path/to/control2.png", "caption": "A caption for image2"} + +If multiple control images are specified, the attribute names should be `control_path_0`, `control_path_1`, etc. + +```json +{"image_path": "/path/to/image1.jpg", "control_path_0": "/path/to/control1_0.png", "control_path_1": "/path/to/control1_1.png", "caption": "A caption for image1"} +{"image_path": "/path/to/image2.jpg", "control_path_0": "/path/to/control2_0.png", "control_path_1": "/path/to/control2_1.png", "caption": "A caption for image2"} +``` + +The control images can also have an alpha channel. In this case, the alpha channel of the image is used as a mask for the latent. This is only for the one frame training of FramePack. + +
+日本語 + +制御画像を持つデータセットです。現時点ではFramePackの単一フレーム学習、FLUX.1 Kontext、FLUX.2、Qwen-Image-Editの学習に使用します。 + +キャプションファイルを用いる場合は`control_directory`を追加で指定してください。制御画像は、画像と同じファイル名(または拡張子のみが異なるファイル名)の、`control_directory`にある画像が使用されます(例:`image_dir/image1.jpg`と`control_dir/image1.png`)。`image_directory`の画像は学習対象の画像(推論時に生成する画像、変化後の画像)としてください。`control_directory`には推論時の開始画像を格納してください。キャプションは`image_directory`へ格納してください。 + +複数枚の制御画像が指定可能です。この場合、制御画像のファイル名(拡張子を除く)へ数字を付与してください。例えば、`image_dir/image1.jpg`と`control_dir/image1_0.png`, `control_dir/image1_1.png`のように指定します。`image1_0000.png`, `image1_0001.png`のように数字を4桁で指定することもできます。 + +メタデータJSONLファイルを使用する場合は、`control_path`を追加してください。複数枚の制御画像を指定する場合は、`control_path_0`, `control_path_1`のように数字を付与してください。 + +FramePackの単一フレーム学習では、制御画像はアルファチャンネルを持つこともできます。この場合、画像のアルファチャンネルはlatentへのマスクとして使用されます。 + +
+ +### Resizing Control Images for Image Dataset / 画像データセットでの制御画像のリサイズ + +By default, the control images are resized to the same size as the target images. You can change the resizing method with the following options: + +- `no_resize_control`: Do not resize the control images. They will be cropped to match the rounding unit of each architecture (for example, 16 pixels). +- `control_resolution`: Resize the control images to the specified resolution. For example, specify `control_resolution = [1024, 1024]`. Aspect Ratio Bucketing will be applied. + +```toml +[[datasets]] +# Image directory or metadata jsonl file as above +image_directory = "/path/to/image_dir" +control_directory = "/path/to/control_dir" +control_resolution = [1024, 1024] +no_resize_control = false +``` + +If both are specified, `control_resolution` is treated as the maximum resolution. That is, if the total number of pixels of the control image exceeds that of `control_resolution`, it will be resized to `control_resolution`. + +The recommended resizing method for control images may vary depending on the architecture. Please refer to the section for each architecture. + +The previous options `flux_kontext_no_resize_control` and `qwen_image_edit_no_resize_control` are still available, but it is recommended to use `no_resize_control`. + +The `qwen_image_edit_control_resolution` is also available, but it is recommended to use `control_resolution`. + + +**The technical details of `no_resize_control`:** + +When this option is specified, the control image is trimmed to a multiple of 16 pixels (depending on the architecture) and converted to latent and passed to the model. + +Each element in the batch must have the same resolution, which is adjusted by advanced Aspect Ratio Bucketing (buckets are divided by the resolution of the target image and also the resolution of the control image). + +
+日本語 + +デフォルトでは、制御画像はターゲット画像と同じサイズにリサイズされます。以下のオプションで、リサイズ方式を変更できます。 + +- `no_resize_control`: 制御画像をリサイズしません。アーキテクチャごとの丸め単位(16ピクセルなど)に合わせてトリミングされます。 +- `control_resolution`: 制御画像を指定した解像度にリサイズします。例えば、`control_resolution = [1024, 1024]`と指定します。Aspect Ratio Bucketingが適用されます。 + +両方が同時に指定されると、`control_resolution`は最大解像度として扱われます。つまり、制御画像の総ピクセル数が`control_resolution`の総ピクセル数を超える場合、`control_resolution`にリサイズされます。 + +アーキテクチャにより、推奨の制御画像のリサイズ方法は異なります。各アーキテクチャの節を参照してください。 + +以前のオプション`flux_kontext_no_resize_control`と`qwen_image_edit_no_resize_control`は使用可能ですが、`no_resize_control`を使用することを推奨します。 + +`qwen_image_edit_control_resolution`も使用可能ですが、`control_resolution`を使用することを推奨します。 + +**`no_resize_control`の技術的な詳細:** + +このオプションが指定された場合、制御画像は16ピクセルの倍数(アーキテクチャに依存)にトリミングされ、latentに変換されてモデルに渡されます。 + +バッチ内の各要素は同じ解像度である必要がありますが、ターゲット画像の解像度と制御画像の解像度の両方でバケットが分割される高度なAspect Ratio Bucketingによって調整されます。 + +
+ +### Sample for Video Dataset with Control Images + +The dataset with control videos is used for training ControlNet models. + +The dataset configuration with caption text files is similar to the video dataset, but with an additional `control_directory` parameter. + +The control video for a video is used from the `control_directory` with the same filename (or different extension) as the video, for example, `video_dir/video1.mp4` and `control_dir/video1.mp4` or `control_dir/video1.mov`. The control video can also be a directory without an extension, for example, `video_dir/video1.mp4` and `control_dir/video1`. + +```toml +[[datasets]] +video_directory = "/path/to/video_dir" +control_directory = "/path/to/control_dir" # required for dataset with control videos +cache_directory = "/path/to/cache_directory" # recommended to set cache directory +target_frames = [1, 25, 45] +frame_extraction = "head" +``` + +The dataset configuration with metadata JSONL file is same as the video dataset, but metadata JSONL file must include the control video paths. The control video path can be a directory containing multiple images. + +```json +{"video_path": "/path/to/video1.mp4", "control_path": "/path/to/control1.mp4", "caption": "A caption for video1"} +{"video_path": "/path/to/video2.mp4", "control_path": "/path/to/control2.mp4", "caption": "A caption for video2"} +``` + +
+日本語 + +制御動画を持つデータセットです。ControlNetモデルの学習に使用します。 + +キャプションを用いる場合のデータセット設定は動画データセットと似ていますが、`control_directory`パラメータが追加されています。上にある例を参照してください。ある動画に対する制御用動画として、動画と同じファイル名(または拡張子のみが異なるファイル名)の、`control_directory`にある動画が使用されます(例:`video_dir/video1.mp4`と`control_dir/video1.mp4`または`control_dir/video1.mov`)。また、拡張子なしのディレクトリ内の、複数枚の画像を制御用動画として使用することもできます(例:`video_dir/video1.mp4`と`control_dir/video1`)。 + +データセット設定でメタデータJSONLファイルを使用する場合は、動画と制御用動画のパスを含める必要があります。制御用動画のパスは、複数枚の画像を含むディレクトリのパスでも構いません。 + +
+ +## Architecture-specific Settings / アーキテクチャ固有の設定 + +The dataset configuration is shared across all architectures. However, some architectures may require additional settings or have specific requirements for the dataset. + +### FramePack + +For FramePack, you can set the latent window size for training. It is recommended to set it to 9 for FramePack training. The default value is 9, so you can usually omit this setting. + +```toml +[[datasets]] +fp_latent_window_size = 9 +``` + +
+日本語 + +学習時のlatent window sizeを指定できます。FramePackの学習においては、9を指定することを推奨します。省略時は9が使用されますので、通常は省略して構いません。 + +
+ +### FramePack One Frame Training + +For the default one frame training of FramePack, you need to set the following parameters in the dataset configuration: + +```toml +[[datasets]] +fp_1f_clean_indices = [0] +fp_1f_target_index = 9 +fp_1f_no_post = false +``` + +**Advanced Settings:** + +**Note that these parameters are still experimental, and the optimal values are not yet known.** The parameters may also change in the future. + +`fp_1f_clean_indices` sets the `clean_indices` value passed to the FramePack model. You can specify multiple indices. `fp_1f_target_index` sets the index of the frame to be trained (generated). `fp_1f_no_post` sets whether to add a zero value as `clean_latent_post`, default is `false` (add zero value). + +The number of control images should match the number of indices specified in `fp_1f_clean_indices`. + +The default values mean that the first image (control image) is at index `0`, and the target image (the changed image) is at index `9`. + +For training with 1f-mc, set `fp_1f_clean_indices` to `[0, 1]` and `fp_1f_target_index` to `9` (or another value). This allows you to use multiple control images to train a single generated image. The control images will be two in this case. + +```toml +[[datasets]] +fp_1f_clean_indices = [0, 1] +fp_1f_target_index = 9 +fp_1f_no_post = false +``` + +For training with kisekaeichi, set `fp_1f_clean_indices` to `[0, 10]` and `fp_1f_target_index` to `1` (or another value). This allows you to use the starting image (the image just before the generation section) and the image following the generation section (equivalent to `clean_latent_post`) to train the first image of the generated video. The control images will be two in this case. `fp_1f_no_post` should be set to `true`. + +```toml +[[datasets]] +fp_1f_clean_indices = [0, 10] +fp_1f_target_index = 1 +fp_1f_no_post = true +``` + +With `fp_1f_clean_indices` and `fp_1f_target_index`, you can specify any number of control images and any index of the target image for training. + +If you set `fp_1f_no_post` to `false`, the `clean_latent_post_index` will be `1 + fp1_latent_window_size`. + +You can also set the `no_2x` and `no_4x` options for cache scripts to disable the clean latents 2x and 4x. + +The 2x indices are `1 + fp1_latent_window_size + 1` for two indices (usually `11, 12`), and the 4x indices are `1 + fp1_latent_window_size + 1 + 2` for sixteen indices (usually `13, 14, ..., 28`), regardless of `fp_1f_no_post` and `no_2x`, `no_4x` settings. + +
+日本語 + +※ **以下のパラメータは研究中で最適値はまだ不明です。** またパラメータ自体も変更される可能性があります。 + +デフォルトの1フレーム学習を行う場合、`fp_1f_clean_indices`に`[0]`を、`fp_1f_target_index`に`9`(または5から15程度の値)を、`no_post`に`false`を設定してください。(記述例は英語版ドキュメントを参照、以降同じ。) + +**より高度な設定:** + +`fp_1f_clean_indices`は、FramePackモデルに渡される `clean_indices` の値を設定します。複数指定が可能です。`fp_1f_target_index`は、学習(生成)対象のフレームのインデックスを設定します。`fp_1f_no_post`は、`clean_latent_post` をゼロ値で追加するかどうかを設定します(デフォルトは`false`で、ゼロ値で追加します)。 + +制御画像の枚数は`fp_1f_clean_indices`に指定したインデックスの数とあわせてください。 + +デフォルトの1フレーム学習では、開始画像(制御画像)1枚をインデックス`0`、生成対象の画像(変化後の画像)をインデックス`9`に設定しています。 + +1f-mcの学習を行う場合は、`fp_1f_clean_indices`に `[0, 1]`を、`fp_1f_target_index`に`9`を設定してください。これにより動画の先頭の2枚の制御画像を使用して、後続の1枚の生成画像を学習します。制御画像は2枚になります。 + +kisekaeichiの学習を行う場合は、`fp_1f_clean_indices`に `[0, 10]`を、`fp_1f_target_index`に`1`(または他の値)を設定してください。これは、開始画像(生成セクションの直前の画像)(`clean_latent_pre`に相当)と、生成セクションに続く1枚の画像(`clean_latent_post`に相当)を使用して、生成動画の先頭の画像(`target_index=1`)を学習します。制御画像は2枚になります。`f1_1f_no_post`は`true`に設定してください。 + +`fp_1f_clean_indices`と`fp_1f_target_index`を応用することで、任意の枚数の制御画像を、任意のインデックスを指定して学習することが可能です。 + +`fp_1f_no_post`を`false`に設定すると、`clean_latent_post_index`は `1 + fp1_latent_window_size` になります。 + +推論時の `no_2x`、`no_4x`に対応する設定は、キャッシュスクリプトの引数で行えます。なお、2xのindexは `1 + fp1_latent_window_size + 1` からの2個(通常は`11, 12`)、4xのindexは `1 + fp1_latent_window_size + 1 + 2` からの16個になります(通常は`13, 14, ..., 28`)です。これらの値は`fp_1f_no_post`や`no_2x`, `no_4x`の設定に関わらず、常に同じです。 + +
+ +### FLUX.1 Kontext [dev] + +The FLUX.1 Kontext dataset configuration uses an image dataset with control images. However, only one control image can be used. + +`fp_1f_*` settings are not used in FLUX.1 Kontext. Masks are also not used. + +If you set `no_resize_control`, it disables resizing of the control image. + +Since FLUX.1 Kontext assumes a fixed [resolution of control images](https://github.com/black-forest-labs/flux/blob/1371b2bc70ac80e1078446308dd5b9a2ebc68c87/src/flux/util.py#L584), it may be better to prepare the control images in advance to match these resolutions and use `no_resize_control`. + +
+日本語 + +FLUX.1 Kontextのデータセット設定は、制御画像を持つ画像データセットを使用します。ただし、制御画像は1枚しか使用できません。 + +`fp_1f_*`の設定はFLUX.1 Kontextでは使用しません。またマスクも使用されません。 + +また、`no_resize_control`を設定すると、制御画像のリサイズを無効にします。 + +FLUX.1 Kontextは[制御画像の固定解像度](https://github.com/black-forest-labs/flux/blob/1371b2bc70ac80e1078446308dd5b9a2ebc68c87/src/flux/util.py#L584)を想定しているため、これらの解像度にあわせて制御画像を事前に用意し、`no_resize_control`を使用する方が良い場合があります。 + +
+ +### Qwen-Image-Edit and Qwen-Image-Edit-2509/2511 + +The Qwen-Image-Edit dataset configuration uses an image dataset with control images. However, only one control image can be used for the standard model (not `2509` or `2511`). + +By default, the control image is resized to the same resolution (and aspect ratio) as the image. + +If you set `no_resize_control`, it disables resizing of the control image. For example, if the image is 960x544 and the control image is 512x512, the control image will remain 512x512. + +Also, you can specify the resolution of the control image separately from the training image resolution by using `control_resolution`. If you want to resize the control images the same as the official code, specify [1024,1024]. **We strongly recommend specifying this value.** + +`no_resize_control` can be specified together with `control_resolution`. + +If `no_resize_control` or `control_resolution` is specified, each control image can have a different resolution. The control image is resized according to the specified settings. + +```toml +[[datasets]] +no_resize_control = false # optional, default is false. Disable resizing of control image +control_resolution = [1024, 1024] # optional, default is None. Specify the resolution of the control image. +``` + +`fp_1f_*` settings are not used in Qwen-Image-Edit. + +
+日本語 + +Qwen-Image-Editのデータセット設定は、制御画像を持つ画像データセットを使用します。複数枚の制御画像も使用可能ですが、無印(`2509`または`2511`でない)モデルでは1枚のみ使用可能です。 + +デフォルトでは、制御画像は画像と同じ解像度(およびアスペクト比)にリサイズされます。 + +`no_resize_control`を設定すると、制御画像のリサイズを無効にします。たとえば、画像が960x544で制御画像が512x512の場合、制御画像は512x512のままになります。 + +また、`control_resolution`を使用することで、制御画像の解像度を学習画像の解像度と異なる値に指定できます。公式のコードと同じように制御画像をリサイズしたい場合は、[1024, 1024]を指定してください。**この値の指定を強く推奨します。** + +`no_resize_control`と `control_resolution`は同時に指定できます。 + +`no_resize_control`または`control_resolution`が指定された場合、各制御画像は異なる解像度を持つことができます。制御画像は指定された設定に従ってリサイズされます。 + +```toml +[[datasets]] +no_resize_control = false # オプション、デフォルトはfalse。制御画像のリサイズを無効にします +control_resolution = [1024, 1024] # オプション、デフォルトはNone。制御画像の解像度を指定します +``` + +`fp_1f_*`の設定はQwen-Image-Editでは使用しません。 + +
+ +### FLUX.2 + +The FLUX.2 dataset configuration uses an image dataset with control images (it can also be trained without control images). Multiple control images can be used. + +`fp_1f_*` settings are not used in FLUX.2. + +If you set `no_resize_control`, it disables resizing of the control images. If you want to follow the official FLUX.2 inference settings, please specify this option. + +You can specify the resolution of the control images separately from the training image resolution by using `control_resolution`. If you want to follow the official FLUX.2 inference settings, specify [2024, 2024] (note that it is not 2048) when there is one control image, and [1024, 1024] when there are multiple control images, together with the `no_resize_control` option. + +
+日本語 + +FLUX.2のデータセット設定は、制御画像を持つ画像データセットを使用します(制御画像なしでも学習できます)。複数枚の制御画像が使用可能です。 + +`fp_1f_*`の設定はFLUX.2では使用しません。 + +`no_resize_control`を設定すると、制御画像のリサイズを無効にします。FLUX.2公式の推論時設定に準拠する場合は、このオプションを指定してください。 + +`control_resolution`を使用して、制御画像の解像度を学習画像の解像度と異なる値に指定できます。FLUX.2公式の推論時設定に準拠する場合は、`no_resize_control`オプションと同時に、制御画像が1枚の場合は`[2024, 2024]`(2048ではないので注意)、制御画像が複数の場合は`[1024, 1024]`を指定してください。 + +
+ +## Specifications + +```toml +# general configurations +[general] +resolution = [960, 544] # optional, [W, H], default is [960, 544]. This is the default resolution for all datasets +caption_extension = ".txt" # optional, default is None. This is the default caption extension for all datasets +batch_size = 1 # optional, default is 1. This is the default batch size for all datasets +num_repeats = 1 # optional, default is 1. Number of times to repeat the dataset. Useful to balance the multiple datasets with different sizes. +enable_bucket = true # optional, default is false. Enable bucketing for datasets +bucket_no_upscale = false # optional, default is false. Disable upscaling for bucketing. Ignored if enable_bucket is false + +### Image Dataset + +# sample image dataset with caption text files +[[datasets]] +image_directory = "/path/to/image_dir" +caption_extension = ".txt" # required for caption text files, if general caption extension is not set +resolution = [960, 544] # required if general resolution is not set +batch_size = 4 # optional, overwrite the default batch size +num_repeats = 1 # optional, overwrite the default num_repeats +enable_bucket = false # optional, overwrite the default bucketing setting +bucket_no_upscale = true # optional, overwrite the default bucketing setting +cache_directory = "/path/to/cache_directory" # optional, default is None to use the same directory as the image directory. NOTE: caching is always enabled +control_directory = "/path/to/control_dir" # optional, required for dataset with control images + +# sample image dataset with metadata **jsonl** file +[[datasets]] +image_jsonl_file = "/path/to/metadata.jsonl" # includes pairs of image files and captions +resolution = [960, 544] # required if general resolution is not set +cache_directory = "/path/to/cache_directory" # required for metadata jsonl file +# caption_extension is not required for metadata jsonl file +# batch_size, num_repeats, enable_bucket, bucket_no_upscale are also available for metadata jsonl file + +### Video Dataset + +# sample video dataset with caption text files +[[datasets]] +video_directory = "/path/to/video_dir" +caption_extension = ".txt" # required for caption text files, if general caption extension is not set +resolution = [960, 544] # required if general resolution is not set + +control_directory = "/path/to/control_dir" # optional, required for dataset with control images + +# following configurations must be set in each [[datasets]] section for video datasets + +target_frames = [1, 25, 79] # required for video dataset. list of video lengths to extract frames. each element must be N*4+1 (N=0,1,2,...) + +# NOTE: Please do not include 1 in target_frames if you are using the frame_extraction "chunk". It will make the all frames to be extracted. + +frame_extraction = "head" # optional, "head" or "chunk", "full", "slide", "uniform". Default is "head" +frame_stride = 1 # optional, default is 1, available for "slide" frame extraction +frame_sample = 4 # optional, default is 1 (same as "head"), available for "uniform" frame extraction +max_frames = 129 # optional, default is 129. Maximum number of frames to extract, available for "full" frame extraction +# batch_size, num_repeats, enable_bucket, bucket_no_upscale, cache_directory are also available for video dataset + +# sample video dataset with metadata jsonl file +[[datasets]] +video_jsonl_file = "/path/to/metadata.jsonl" # includes pairs of video files and captions + +target_frames = [1, 79] + +cache_directory = "/path/to/cache_directory" # required for metadata jsonl file +# frame_extraction, frame_stride, frame_sample, max_frames are also available for metadata jsonl file +``` + + + +The metadata with .json file will be supported in the near future. diff --git a/VRGDG_Musubi-tuner/docs/flux_2.md b/VRGDG_Musubi-tuner/docs/flux_2.md new file mode 100644 index 0000000000000000000000000000000000000000..2623cb00f0399847e46478e2146e85284328954e --- /dev/null +++ b/VRGDG_Musubi-tuner/docs/flux_2.md @@ -0,0 +1,285 @@ +# FLUX.2 + +## Overview / 概要 + +This document describes the usage of the [FLUX.2](https://huggingface.co/black-forest-labs/FLUX.2-dev) \[dev\] architecture within the Musubi Tuner framework. FLUX.2-dev is an image generation model and edit model that can take a reference image as input. + +This feature is experimental. + +Latent pre-caching, training, and inference options can be found in the `--help` output. Many options are shared with HunyuanVideo, so refer to the [HunyuanVideo documentation](./hunyuan_video.md) as needed. + +
+日本語 + +
+ +## Download the model / モデルのダウンロード + +You need to download the DiT, AE, Text Encoder models. + +### FLUX.2 [dev] + +- **DiT, AE**: Download from the [black-forest-labs/FLUX.2-dev](https://huggingface.co/black-forest-labs/FLUX.2-dev) repository. Use `flux2-dev.safetensors` and `ae.safetensors`. The weights in the subfolder are in Diffusers format and cannot be used. +- **Text Encoder (Mistral 3)**: Download all the split files from the [black-forest-labs/FLUX.2-dev](https://huggingface.co/black-forest-labs/FLUX.2-dev) repository and specify the first file (e.g., `00001-of-00010.safetensors`) in the arguments. + +
+日本語 + +DiT, AE, Text Encoder のモデルをダウンロードする必要があります。 + +- **DiT, AE**: [black-forest-labs/FLUX.2-dev](https://huggingface.co/black-forest-labs/FLUX.2-dev) リポジトリからダウンロードしてください。`flux2-dev.safetensors` および `ae.safetensors` を使用してください。サブフォルダ内の重みはDiffusers形式なので使用できません。 +- **Text Encoder (Mistral 3)**: Download all the split files from the [black-forest-labs/FLUX.2-dev](https://huggingface.co/black-forest-labs/FLUX.2-dev) repository and specify the first file (e.g., `00001-of-00010.safetensors`) in the arguments. +
+ +### FLUX.2 [klein] 4B / base 4B + +- **DiT 4B**: Download from the [black-forest-labs/FLUX.2-klein-4B](https://huggingface.co/black-forest-labs/FLUX.2-klein-4B) repository. Use `flux2-klein-4b.safetensors`. +- **DiT base 4B**: Download from the [black-forest-labs/FLUX.2-klein-base-4B](https://huggingface.co/black-forest-labs/FLUX.2-klein-base-4B) repository. Use `flux2-klein-base-4b.safetensors`. +- **AE**: Download from the [black-forest-labs/FLUX.2](https://huggingface.co/black-forest-labs/FLUX.2-dev) repository. Use `ae.safetensors`. `vae/diffusion_pytorch_model.safetensors` in the subfolder is in Diffusers format and cannot be used. +- **Qwen3 4B Text Encoder**: Download all the split files from the [black-forest-labs/FLUX.2-klein-4B](https://huggingface.co/black-forest-labs/FLUX.2-klein-4B) repository and specify the first file (e.g., `00001-of-00002.safetensors`) in the arguments. + +If you already have the weights for Qwen3 4B used in Z-Image, you can use them as is. Refer to the [Z-Image documentation](./zimage.md#download-the-model--モデルのダウンロード) for details. + +
+日本語 + +- **DiT 4B**: [black-forest-labs/FLUX.2-klein-4B](https://huggingface.co/black-forest-labs/FLUX.2-klein-4B) リポジトリからダウンロードしてください。`flux2-klein-4b.safetensors` を使用してください。 +- **DiT base 4B**: [black-forest-labs/FLUX.2-klein-base-4B](https://huggingface.co/black-forest-labs/FLUX.2-klein-base-4B) リポジトリからダウンロードしてください。`flux2-klein-base-4b.safetensors` を使用してください。 +- **AE**: [black-forest-labs/FLUX.2](https://huggingface.co/black-forest-labs/FLUX.2-dev) リポジトリからダウンロードしてください。`ae.safetensors` を使用してください。サブフォルダ内の `vae/diffusion_pytorch_model.safetensors` はDiffusers形式なので使用できません。 +- **Qwen3 4B Text Encoder**: [black-forest-labs/FLUX.2-klein-4B](https://huggingface.co/black-forest-labs/FLUX.2-klein-4B) リポジトリから分割されたすべてのファイルをダウンロードし、最初のファイル(例:`00001-of-00002.safetensors`)を引数で指定してください。 + +Qwen3 4Bの重みは、すでにZ-Imageで用いているものがあればそのまま使用可能です。[Z-Imageのドキュメント](./zimage.md#download-the-model--モデルのダウンロード)を参照してください。 + +
+ +### FLUX.2 [klein] 9B / base 9B + +- **DiT 9B**: Download from the [black-forest-labs/FLUX.2-klein-9B](https://huggingface.co/black-forest-labs/FLUX.2-klein-9B) repository. Use `flux2-klein-9b.safetensors`. +- **DiT base 9B**: Download from the [black-forest-labs/FLUX.2-klein-base-9B](https://huggingface.co/black-forest-labs/FLUX.2-klein-base-9B) repository. Use `flux2-klein-base-9b.safetensors`. +- **AE**: Download from the [black-forest-labs/FLUX.2](https://huggingface.co/black-forest-labs/FLUX.2-dev) repository. Use `ae.safetensors`. `vae/diffusion_pytorch_model.safetensors` in the subfolder is in Diffusers format and cannot be used. +- **Qwen3 8B Text Encoder**: Download all the split files from the [black-forest-labs/FLUX.2-klein-9B](https://huggingface.co/black-forest-labs/FLUX.2-klein-9B) repository and specify the first file (e.g., `00001-of-00004.safetensors`) in the arguments. + +
+日本語 + +- **DiT 9B**: [black-forest-labs/FLUX.2-klein-9B](https://huggingface.co/black-forest-labs/FLUX.2-klein-9B) リポジトリからダウンロードしてください。`flux2-klein-9b.safetensors` を使用してください。 +- **DiT base 9B**: [black-forest-labs/FLUX.2-klein-base-9B](https://huggingface.co/black-forest-labs/FLUX.2-klein-base-9B) リポジトリからダウンロードしてください。`flux2-klein-base-9b.safetensors` を使用してください。 +- **AE**: [black-forest-labs/FLUX.2](https://huggingface.co/black-forest-labs/FLUX.2-dev) リポジトリからダウンロードしてください。`ae.safetensors` を使用してください。サブフォルダ内の `vae/diffusion_pytorch_model.safetensors` はDiffusers形式なので使用できません。 +- **Qwen3 8B Text Encoder**: [black-forest-labs/FLUX.2-klein-9B](https://huggingface.co/black-forest-labs/FLUX.2-klein-9B) リポジトリから分割されたすべてのファイルをダウンロードし、最初のファイル(例:`00001-of-00004.safetensors`)を引数で指定してください。 +
+ + +## Specifying Model Version / モデルバージョンの指定 + +When specifying the model version in various scripts, use the following options: + +|type|version|sampling guidance scale|num sampling steps| +|----|--------|----|----| +|flux.2-dev|`--model_version dev`|4.0|50| +|flux.2-klein-4b|`--model_version klein-4b`|1.0|4| +|flux.2-klein-base-4b|`--model_version klein-base-4b`|4.0|50| +|flux.2-klein-9b|`--model_version klein-9b`|1.0|4| +|flux.2-klein-base-9b|`--model_version klein-base-9b`|4.0|50| + +For model training, it is recommended to use klein base 4B or 9B. The dev and klein 4B/9B are distilled models primarily intended for inference. + +
+日本語 + +それぞれのスクリプトでモデルバージョンを指定する際には、英語版の文章を参考にして`--model_version`オプションを使用してください。 + +モデルの学習を行う場合は、klein base 4Bまたは9Bを使用することをお勧めします。dev、およびklein 4B/9Bは蒸留モデルであり、主に推論用です。 + +
+ +## Pre-caching / 事前キャッシング + +### Latent Pre-caching / latentの事前キャッシング + +Latent pre-caching uses a dedicated script for FLUX.2. + +```bash +python src/musubi_tuner/flux_2_cache_latents.py \ + --dataset_config path/to/toml \ + --vae path/to/ae_model \ + --model_version dev +``` + +- Note that the `--vae` argument is required, not `--ae`. +- Uses `flux_2_cache_latents.py`. +- The dataset must be an image dataset. +- Use the `--model_version` option for Flux.2 Klein training (if omitted, defaults to `dev`). +- The `control_images` in the dataset config is used as the reference image. See [Dataset Config](./dataset_config.md#flux1-kontext-dev) for details. +- `--vae_dtype` option is available to specify the VAE weight data type. Default is `float32`, `bfloat16` can also be specified. Specifying `bfloat16` reduces VRAM usage. + +
+日本語 + +latentの事前キャッシングはFLUX.2専用のスクリプトを使用します。 + +- `flux_2_cache_latents.py`を使用します。 +- `--ae`ではなく、`--vae`引数を指定してください。 +- データセットは画像データセットである必要があります。 +- データセット設定の`control_images`が参照画像として使用されます。詳細は[データセット設定](./dataset_config.md#flux1-kontext-dev)を参照してください。 +- `--vae_dtype`オプションは、VAEの重みデータ型を指定するためのオプションです。デフォルトは`float32`で、`bfloat16`も指定可能です。`bfloat16`を指定するとVRAM使用量が削減されます。 + +
+ +### Text Encoder Output Pre-caching / テキストエンコーダー出力の事前キャッシング + +Text encoder output pre-caching also uses a dedicated script. + +```bash +python src/musubi_tuner/flux_2_cache_text_encoder_outputs.py \ + --dataset_config path/to/toml \ + --text_encoder path/to/text_encoder \ + --batch_size 16 \ + --model_version dev +``` + +- Uses `flux_2_cache_text_encoder_outputs.py`. +- Requires `--text_encoder` argument +- Use the `--model_version` option for Flux.2 Klein training (if omitted, defaults to `dev`). +- Use `--fp8_text_encoder` option to run the Text Encoder in fp8 mode for VRAM savings. +- The larger the batch size, the more VRAM is required. Adjust `--batch_size` according to your VRAM capacity. + +
+日本語 + +テキストエンコーダー出力の事前キャッシングも専用のスクリプトを使用します。 + +- `flux_2_cache_text_encoder_outputs.py`を使用します。 +- テキストエンコーダーをfp8モードで実行するための`--fp8_text_encoder`オプションを使用します。 +- バッチサイズが大きいほど、より多くのVRAMが必要です。VRAM容量に応じて`--batch_size`を調整してください。 + +
+ +## Training / 学習 + +Training uses a dedicated script `flux_2_train_network.py`. + +```bash +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 src/musubi_tuner/flux_2_train_network.py \ + --model_version dev \ + --dit path/to/dit_model \ + --vae path/to/ae_model \ + --text_encoder path/to/text_encoder \ + --dataset_config path/to/toml \ + --sdpa --mixed_precision bf16 \ + --timestep_sampling flux2_shift --weighting_scheme none \ + --optimizer_type adamw8bit --learning_rate 1e-4 --gradient_checkpointing \ + --max_data_loader_n_workers 2 --persistent_data_loader_workers \ + --network_module networks.lora_flux_2 --network_dim 32 \ + --max_train_epochs 16 --save_every_n_epochs 1 --seed 42 \ + --output_dir path/to/output_dir --output_name name-of-lora +``` + +- Uses `flux_2_train_network.py`. +- **Requires** specifying `--vae` (not `--ae`), `--text_encoder` +- **Requires** specifying `--network_module networks.lora_flux_2`. +- `--mixed_precision bf16` is recommended for FLUX.2 training. +- `--timestep_sampling flux2_shift` is recommended for FLUX.2. +- Use the `--model_version` option for Flux.2 Klein training (if omitted, defaults to `dev`). +- Memory saving options like `--fp8_base --fp8_scaled` (for DiT, specify both) and `--fp8_text_encoder` (for Text Encoder) are available. `--fp8_scaled` is recommended when using `--fp8_base` for DiT. +- `--gradient_checkpointing` and `--gradient_checkpointing_cpu_offload` are available for memory savings. See [HunyuanVideo documentation](./hunyuan_video.md#memory-optimization) for details. +- `--vae_dtype` option is available to specify the VAE weight data type. Default is `float32`, `bfloat16` can also be specified. +- Instead of `--sdpa`, `--xformers` and `--flash_attn` can also be used. Make sure the related libraries are installed. + +`--fp8_text_encoder` option is not available for dev (Mistral 3). + +Some blocks can be offloaded to CPU for memory savings using the `--blocks_to_swap` option. See [HunyuanVideo documentation](./hunyuan_video.md#memory-optimization) for details. + +In FLUX.2, since DoubleStreamBlock uses more memory than SingleStreamBlock and the number of each block varies by model, the actual number of offloaded blocks is automatically adjusted (double block + single block * 2 = number of swap blocks). + +The maximum values of `blocks_to_swap` per model when combined with the `--fp8_base --fp8_scaled` options are as follows: + +|Model Type|Maximum blocks_to_swap| +|----|----| +|flux.2-dev|29| +|flux.2-klein-4b|13| +|flux.2-klein-9b|16| + +
+日本語 + +FLUX.2の学習は専用のスクリプト`flux_2_train_network.py`を使用します。 + +- `flux_2_train_network.py`を使用します。 +- `--ae`、`--text_encoder` を指定する必要があります。 +- `--network_module networks.lora_flux_2`を指定する必要があります。 +- FLUX.2の学習には`--mixed_precision bf16`を推奨します。 +- FLUX.2には`--timestep_sampling flux2_shift`を推奨します。 +- `--fp8_base --fp8_scaled`(DiT用、両方指定してください)や`--fp8_text_encoder`(テキストエンコーダー用)などのメモリ節約オプションが利用可能です。`--fp8_base`をDiTに使用する場合は、`--fp8_scaled`を推奨します。 +- メモリ節約のために`--gradient_checkpointing`が利用可能です。 +- `--vae_dtype`オプションは、VAEの重みデータ型を指定するためのオプションです。デフォルトは`float32`で、`bfloat16`も指定可能です。 +- `--sdpa`の代わりに`--xformers`および`--flash_attn`を使用することも可能です。関連するライブラリがインストールされていることを確認してください。 + +`--fp8_text_encoder`オプションはdev(Mistral 3)では使用できません。 + +一部のブロックをメモリ節約のためにCPUにオフロードする`--blocks_to_swap`オプションも利用可能です。詳細は[HunyuanVideoのドキュメント](./hunyuan_video.md#memory-optimization)を参照してください。 + +FLUX.2ではDoubleStreamBlockのメモリ使用量がSingleStreamBlockよりも大きいのと、それぞれのブロック数がモデルごとに異なるため、実際にオフロードされるブロック数は自動調整されます(double block + single block * 2 = swap block数)。 + +`--fp8_base --fp8_scaled`オプションと組み合わせたときの、モデルごとの`blocks_to_swap`の最大値は以下の通りです。 + +|モデル種類|blocks_to_swapの最大値| +|----|----| +|flux.2-dev|29| +|flux.2-klein-4b|13| +|flux.2-klein-9b|16| + +
+ +## Inference / 推論 + +Inference uses a dedicated script `flux_2_generate_image.py`. + +```bash +python src/musubi_tuner/flux_2_generate_image.py \ + --model_version dev \ + --dit path/to/dit_model \ + --vae path/to/ae_model \ + --text_encoder path/to/text_encoder \ + --control_image_path path/to/control_image.jpg \ + --prompt "A cat" \ + --image_size 1024 1024 --infer_steps 50 \ + --fp8_scaled \ + --save_path path/to/save/dir --output_type images \ + --seed 1234 --lora_multiplier 1.0 --lora_weight path/to/lora.safetensors +``` + +- Uses `flux_2_generate_image.py`. +- **Requires** specifying `--vae`, `--text_encoder` +- **Requires** specifying `--control_image_path` for the reference image. +- Use the `--model_version` option for Flux.2 Klein inference (if omitted, defaults to `dev`). +- `--no_resize_control`: By default, the control image is resized to the recommended resolution for FLUX.2. If you specify this option, this resizing is skipped, and the image is used as-is. + + This feature is not officially supported by FLUX.2, but it is available for experimental use. + +- `--image_size` is the size of the generated image, height and width are specified in that order. +- `--prompt`: Prompt for generation. +- `--fp8_scaled` option is available for DiT to reduce memory usage. Quality may be slightly lower. `--fp8_text_encoder` option is available to reduce memory usage of Text Encoder. `--fp8` alone is also an option for DiT but `--fp8_scaled` potentially offers better quality. +- LoRA loading options (`--lora_weight`, `--lora_multiplier`, `--include_patterns`, `--exclude_patterns`) are available. `--lycoris` is also supported. +- `--embedded_cfg_scale` (default 2.5) controls the distilled guidance scale. +- `--save_merged_model` option is available to save the DiT model after merging LoRA weights. Inference is skipped if this is specified. + +
+日本語 + +FLUX.2の推論は専用のスクリプト`flux_2_generate_image.py`を使用します。 + +- `flux_2_generate_image.py`を使用します。 +- `--vae`、`--text_encoder` を指定する必要があります。 +- `--control_image_path`を指定する必要があります(参照画像)。 +- `--no_resize_control`: デフォルトでは、参照画像はFLUX.2の推奨解像度にリサイズされます。このオプションを指定すると、このリサイズはスキップされ、画像はそのままのサイズで使用されます。 + + この機能はFLUX.2では公式にサポートされていませんが、実験的に使用可能です。 + +- `--image_size`は生成する画像のサイズで、高さと幅をその順番で指定します。 +- `--prompt`: 生成用のプロンプトです。 +- DiTのメモリ使用量を削減するために、`--fp8_scaled`オプションを指定可能です。品質はやや低下する可能性があります。またText Encoder 1のメモリ使用量を削減するために、`--fp8_text_encoder`オプションを指定可能です。DiT用に`--fp8`単独のオプションも用意されていますが、`--fp8_scaled`の方が品質が良い可能性があります。 +- LoRAの読み込みオプション(`--lora_weight`、`--lora_multiplier`、`--include_patterns`、`--exclude_patterns`)が利用可能です。LyCORISもサポートされています。 +- `--embedded_cfg_scale`(デフォルト2.5)は、蒸留されたガイダンススケールを制御します。 +- `--save_merged_model`オプションは、LoRAの重みをマージした後にDiTモデルを保存するためのオプションです。これを指定すると推論はスキップされます。 + +
\ No newline at end of file diff --git a/VRGDG_Musubi-tuner/docs/flux_kontext.md b/VRGDG_Musubi-tuner/docs/flux_kontext.md new file mode 100644 index 0000000000000000000000000000000000000000..e757c0643de33c1d4e1b126700d1ff09e4010ab9 --- /dev/null +++ b/VRGDG_Musubi-tuner/docs/flux_kontext.md @@ -0,0 +1,190 @@ +# FLUX.1 Kontext + +## Overview / 概要 + +This document describes the usage of the [FLUX.1 Kontext](https://github.com/black-forest-labs/flux) \[dev\] architecture within the Musubi Tuner framework. FLUX.1 Kontext is an image generation model that can take a reference image as input. + +This feature is experimental. + +Latent pre-caching, training, and inference options can be found in the `--help` output. Many options are shared with HunyuanVideo, so refer to the [HunyuanVideo documentation](./hunyuan_video.md) as needed. + +
+日本語 + +このドキュメントは、Musubi Tunerフレームワーク内での[FLUX.1 Kontext](https://github.com/black-forest-labs/flux) \[dev\] アーキテクチャの使用法について説明しています。FLUX.1 Kontextは、参照画像をコンテキストとして入力できる画像生成モデルです。 + +この機能は実験的なものです。 + +事前キャッシング、学習、推論のオプションは`--help`で確認してください。HunyuanVideoと共通のオプションが多くありますので、必要に応じて[HunyuanVideoのドキュメント](./hunyuan_video.md)も参照してください。 + +
+ +## Download the model / モデルのダウンロード + +You need to download the DiT, AE, Text Encoder 1 (T5-XXL), and Text Encoder 2 (CLIP-L) models. + +- **DiT, AE**: Download from the [black-forest-labs/FLUX.1-kontext](https://huggingface.co/black-forest-labs/FLUX.1-Kontext-dev) repository. Use `flux1-kontext-dev.safetensors` and `ae.safetensors`. The weights in the subfolder are in Diffusers format and cannot be used. +- **Text Encoder 1 (T5-XXL), Text Encoder 2 (CLIP-L)**: Download from the [ComfyUI FLUX Text Encoders](https://huggingface.co/comfyanonymous/flux_text_encoders) repository. Please use `t5xxl_fp16.safetensors` for T5-XXL. Thanks to ComfyUI for providing these models. + +
+日本語 + +DiT, AE, Text Encoder 1 (T5-XXL), Text Encoder 2 (CLIP-L) のモデルをダウンロードする必要があります。 + +- **DiT, AE**: [black-forest-labs/FLUX.1-kontext](https://huggingface.co/black-forest-labs/FLUX.1-Kontext-dev) リポジトリからダウンロードしてください。`flux1-kontext-dev.safetensors` および `ae.safetensors` を使用してください。サブフォルダ内の重みはDiffusers形式なので使用できません。 +- **Text Encoder 1 (T5-XXL), Text Encoder 2 (CLIP-L)**: [ComfyUIのFLUX Text Encoders](https://huggingface.co/comfyanonymous/flux_text_encoders) リポジトリからダウンロードしてください。T5-XXLには`t5xxl_fp16.safetensors`を使用してください。これらのモデルをご提供いただいたComfyUIに感謝します。 +
+ +## Pre-caching / 事前キャッシング + +### Latent Pre-caching / latentの事前キャッシング + +Latent pre-caching uses a dedicated script for FLUX.1 Kontext. + +```bash +python src/musubi_tuner/flux_kontext_cache_latents.py \ + --dataset_config path/to/toml \ + --vae path/to/ae_model +``` + +- Note that the `--vae` argument is required, not `--ae`. +- Uses `flux_kontext_cache_latents.py`. +- The dataset must be an image dataset. +- The `control_images` in the dataset config is used as the reference image. See [Dataset Config](./dataset_config.md#flux1-kontext-dev) for details. + +
+日本語 + +latentの事前キャッシングはFLUX.1 Kontext専用のスクリプトを使用します。 + +- `flux_kontext_cache_latents.py`を使用します。 +- `--ae`ではなく、`--vae`引数を指定してください。 +- データセットは画像データセットである必要があります。 +- データセット設定の`control_images`が参照画像として使用されます。詳細は[データセット設定](./dataset_config.md#flux1-kontext-dev)を参照してください。 + +
+ +### Text Encoder Output Pre-caching / テキストエンコーダー出力の事前キャッシング + +Text encoder output pre-caching also uses a dedicated script. + +```bash +python src/musubi_tuner/flux_kontext_cache_text_encoder_outputs.py \ + --dataset_config path/to/toml \ + --text_encoder1 path/to/text_encoder1 \ + --text_encoder2 path/to/text_encoder2 \ + --batch_size 16 +``` + +- Uses `flux_kontext_cache_text_encoder_outputs.py`. +- Requires both `--text_encoder1` (T5) and `--text_encoder2` (CLIP) arguments. +- Use `--fp8_t5` option to run the T5 Text Encoder in fp8 mode for VRAM savings. +- The larger the batch size, the more VRAM is required. Adjust `--batch_size` according to your VRAM capacity. + +
+日本語 + +テキストエンコーダー出力の事前キャッシングも専用のスクリプトを使用します。 + +- `flux_kontext_cache_text_encoder_outputs.py`を使用します。 +- T5とCLIPの両方の引数が必要です。 +- T5テキストエンコーダーをfp8モードで実行するための`--fp8_t5`オプションを使用します。 +- バッチサイズが大きいほど、より多くのVRAMが必要です。VRAM容量に応じて`--batch_size`を調整してください。 + +
+ +## Training / 学習 + +Training uses a dedicated script `flux_kontext_train_network.py`. + +```bash +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 src/musubi_tuner/flux_kontext_train_network.py \ + --dit path/to/dit_model \ + --vae path/to/ae_model \ + --text_encoder1 path/to/text_encoder1 \ + --text_encoder2 path/to/text_encoder2 \ + --dataset_config path/to/toml \ + --sdpa --mixed_precision bf16 \ + --timestep_sampling flux_shift --weighting_scheme none \ + --optimizer_type adamw8bit --learning_rate 1e-4 --gradient_checkpointing \ + --max_data_loader_n_workers 2 --persistent_data_loader_workers \ + --network_module networks.lora_flux --network_dim 32 \ + --max_train_epochs 16 --save_every_n_epochs 1 --seed 42 \ + --output_dir path/to/output_dir --output_name name-of-lora +``` + +- Uses `flux_kontext_train_network.py`. +- **Requires** specifying `--vae` (not `--ae`), `--text_encoder1`, and `--text_encoder2`. +- **Requires** specifying `--network_module networks.lora_flux`. +- `--mixed_precision bf16` is recommended for FLUX.1 Kontext training. +- `--timestep_sampling flux_shift` is recommended for FLUX.1 Kontext. +- Memory saving options like `--fp8` (for DiT) and `--fp8_t5` (for Text Encoder 1) are available. `--fp8_scaled` is recommended when using `--fp8` for DiT. +- `--gradient_checkpointing` and `--gradient_checkpointing_cpu_offload` are available for memory savings. See [HunyuanVideo documentation](./hunyuan_video.md#memory-optimization) for details. + +
+日本語 + +FLUX.1 Kontextの学習は専用のスクリプト`flux_kontext_train_network.py`を使用します。 + +- `flux_kontext_train_network.py`を使用します。 +- `--ae`、`--text_encoder1`、`--text_encoder2`を指定する必要があります。 +- `--network_module networks.lora_flux`を指定する必要があります。 +- FLUX.1 Kontextの学習には`--mixed_precision bf16`を推奨します。 +- FLUX.1 Kontextには`--timestep_sampling flux_shift`を推奨します。 +- `--fp8`(DiT用)や`--fp8_t5`(テキストエンコーダー1用)などのメモリ節約オプションが利用可能です。`--fp8_scaled`を使用することをお勧めします。 +- メモリ節約のために`--gradient_checkpointing`が利用可能です。 + +
+ +## Inference / 推論 + +Inference uses a dedicated script `flux_kontext_generate_image.py`. + +```bash +python src/musubi_tuner/flux_kontext_generate_image.py \ + --dit path/to/dit_model \ + --vae path/to/ae_model \ + --text_encoder1 path/to/text_encoder1 \ + --text_encoder2 path/to/text_encoder2 \ + --control_image_path path/to/control_image.jpg \ + --prompt "A cat" \ + --image_size 1024 1024 --infer_steps 25 \ + --attn_mode sdpa --fp8_scaled \ + --save_path path/to/save/dir --output_type images \ + --seed 1234 --lora_multiplier 1.0 --lora_weight path/to/lora.safetensors +``` + +- Uses `flux_kontext_generate_image.py`. +- **Requires** specifying `--vae`, `--text_encoder1`, and `--text_encoder2`. +- **Requires** specifying `--control_image_path` for the reference image. +- `--no_resize_control`: By default, the control image is resized to the recommended resolution for FLUX.1 Kontext. If you specify this option, this resizing is skipped, and the image is used as-is. + + This feature is not officially supported by FLUX.1 Kontext, but it is available for experimental use. + +- `--image_size` is the size of the generated image, height and width are specified in that order. +- `--prompt`: Prompt for generation. +- `--fp8_scaled` option is available for DiT to reduce memory usage. Quality may be slightly lower. `--fp8_t5` option is available to reduce memory usage of Text Encoder 1. `--fp8` alone is also an option for DiT but `--fp8_scaled` potentially offers better quality. +- LoRA loading options (`--lora_weight`, `--lora_multiplier`, `--include_patterns`, `--exclude_patterns`) are available. `--lycoris` is also supported. +- `--embedded_cfg_scale` (default 2.5) controls the distilled guidance scale. +- `--save_merged_model` option is available to save the DiT model after merging LoRA weights. Inference is skipped if this is specified. + +
+日本語 + +FLUX.1 Kontextの推論は専用のスクリプト`flux_kontext_generate_image.py`を使用します。 + +- `flux_kontext_generate_image.py`を使用します。 +- `--vae`、`--text_encoder1`、`--text_encoder2`を指定する必要があります。 +- `--control_image_path`を指定する必要があります(参照画像)。 +- `--no_resize_control`: デフォルトでは、参照画像はFLUX.1 Kontextの推奨解像度にリサイズされます。このオプションを指定すると、このリサイズはスキップされ、画像はそのままのサイズで使用されます。 + + この機能はFLUX.1 Kontextでは公式にサポートされていませんが、実験的に使用可能です。 + +- `--image_size`は生成する画像のサイズで、高さと幅をその順番で指定します。 +- `--prompt`: 生成用のプロンプトです。 +- DiTのメモリ使用量を削減するために、`--fp8_scaled`オプションを指定可能です。品質はやや低下する可能性があります。またText Encoder 1のメモリ使用量を削減するために、`--fp8_t5`オプションを指定可能です。DiT用に`--fp8`単独のオプションも用意されていますが、`--fp8_scaled`の方が品質が良い可能性があります。 +- LoRAの読み込みオプション(`--lora_weight`、`--lora_multiplier`、`--include_patterns`、`--exclude_patterns`)が利用可能です。LyCORISもサポートされています。 +- `--embedded_cfg_scale`(デフォルト2.5)は、蒸留されたガイダンススケールを制御します。 +- `--save_merged_model`オプションは、LoRAの重みをマージした後にDiTモデルを保存するためのオプションです。これを指定すると推論はスキップされます。 + +
\ No newline at end of file diff --git a/VRGDG_Musubi-tuner/docs/framepack.md b/VRGDG_Musubi-tuner/docs/framepack.md new file mode 100644 index 0000000000000000000000000000000000000000..e8e79c4ea813662dfa39909143806cf6aca53d21 --- /dev/null +++ b/VRGDG_Musubi-tuner/docs/framepack.md @@ -0,0 +1,618 @@ +# FramePack + +## Overview / 概要 + +This document describes the usage of the [FramePack](https://github.com/lllyasviel/FramePack) architecture within the Musubi Tuner framework. FramePack is a novel video generation architecture developed by lllyasviel. + +Key differences from HunyuanVideo: +- FramePack only supports Image-to-Video (I2V) generation. Text-to-Video (T2V) is not supported. +- It utilizes a different DiT model architecture and requires an additional Image Encoder. VAE is same as HunyuanVideo. Text Encoders seem to be the same as HunyuanVideo but we employ the original FramePack method to utilize them. +- Caching and training scripts are specific to FramePack (`fpack_*.py`). +- Due to its progressive generation nature, VRAM usage can be significantly lower, especially for longer videos, compared to other architectures. + +The official documentation does not provide detailed explanations on how to train the model, but it is based on the FramePack implementation and paper. + +This feature is experimental. + +For one-frame inference and training, see [here](./framepack_1f.md). + +Latent pre-caching, training, and inference options can be found in the `--help` output. Many options are shared with HunyuanVideo, so refer to the [HunyuanVideo documentation](./hunyuan_video.md) as needed. + +
+日本語 + +このドキュメントは、Musubi Tunerフレームワーク内での[FramePack](https://github.com/lllyasviel/FramePack) アーキテクチャの使用法について説明しています。FramePackは、lllyasviel氏にによって開発された新しいビデオ生成アーキテクチャです。 + +HunyuanVideoとの主な違いは次のとおりです。 +- FramePackは、画像からビデオ(I2V)生成のみをサポートしています。テキストからビデオ(T2V)はサポートされていません。 +- 異なるDiTモデルアーキテクチャを使用し、追加の画像エンコーダーが必要です。VAEはHunyuanVideoと同じです。テキストエンコーダーはHunyuanVideoと同じと思われますが、FramePack公式と同じ方法で推論を行っています。 +- キャッシングと学習スクリプトはFramePack専用(`fpack_*.py`)です。 +- セクションずつ生成するため、他のアーキテクチャと比較して、特に長いビデオの場合、VRAM使用量が大幅に少なくなる可能性があります。 + +学習方法について公式からは詳細な説明はありませんが、FramePackの実装と論文を参考にしています。 + +この機能は実験的なものです。 + +1フレーム推論、学習については[こちら](./framepack_1f.md)を参照してください。 + +事前キャッシング、学習、推論のオプションは`--help`で確認してください。HunyuanVideoと共通のオプションが多くありますので、必要に応じて[HunyuanVideoのドキュメント](./hunyuan_video.md)も参照してください。 + +
+ +## Download the model / モデルのダウンロード + +You need to download the DiT, VAE, Text Encoder 1 (LLaMA), Text Encoder 2 (CLIP), and Image Encoder (SigLIP) models specifically for FramePack. Several download options are available for each component. + +***Note:** The weights are publicly available on the following page: [maybleMyers/framepack_h1111](https://huggingface.co/maybleMyers/framepack_h1111) (except for FramePack-F1). Thank you maybleMyers! + +### DiT Model + +Choose one of the following methods: + +1. **From lllyasviel's Hugging Face repo:** Download the three `.safetensors` files (starting with `diffusion_pytorch_model-00001-of-00003.safetensors`) from [lllyasviel/FramePackI2V_HY](https://huggingface.co/lllyasviel/FramePackI2V_HY). Specify the path to the first file (`...-00001-of-00003.safetensors`) as the `--dit` argument. For FramePack-F1, download from [lllyasviel/FramePack_F1_I2V_HY_20250503](https://huggingface.co/lllyasviel/FramePack_F1_I2V_HY_20250503). + +2. **From local FramePack installation:** If you have cloned and run the official FramePack repository, the model might be downloaded locally. Specify the path to the snapshot directory, e.g., `path/to/FramePack/hf_download/hub/models--lllyasviel--FramePackI2V_HY/snapshots/`. FramePack-F1 is also available in the same way. + +3. **From Kijai's Hugging Face repo:** Download the single file `FramePackI2V_HY_bf16.safetensors` from [Kijai/HunyuanVideo_comfy](https://huggingface.co/Kijai/HunyuanVideo_comfy/blob/main/FramePackI2V_HY_bf16.safetensors). Specify the path to this file as the `--dit` argument. No FramePack-F1 model is available here currently. + +### VAE Model + +Choose one of the following methods: + +1. **Use official HunyuanVideo VAE:** Follow the instructions in the main [README.md](../README.md#model-download). +2. **From hunyuanvideo-community Hugging Face repo:** Download `vae/diffusion_pytorch_model.safetensors` from [hunyuanvideo-community/HunyuanVideo](https://huggingface.co/hunyuanvideo-community/HunyuanVideo). +3. **From local FramePack installation:** If you have cloned and run the official FramePack repository, the VAE might be downloaded locally within the HunyuanVideo community model snapshot. Specify the path to the snapshot directory, e.g., `path/to/FramePack/hf_download/hub/models--hunyuanvideo-community--HunyuanVideo/snapshots/`. + +### Text Encoder 1 (LLaMA) Model + +Choose one of the following methods: + +1. **From Comfy-Org Hugging Face repo:** Download `split_files/text_encoders/llava_llama3_fp16.safetensors` from [Comfy-Org/HunyuanVideo_repackaged](https://huggingface.co/Comfy-Org/HunyuanVideo_repackaged). +2. **From hunyuanvideo-community Hugging Face repo:** Download the four `.safetensors` files (starting with `text_encoder/model-00001-of-00004.safetensors`) from [hunyuanvideo-community/HunyuanVideo](https://huggingface.co/hunyuanvideo-community/HunyuanVideo). Specify the path to the first file (`...-00001-of-00004.safetensors`) as the `--text_encoder1` argument. +3. **From local FramePack installation:** (Same as VAE) Specify the path to the HunyuanVideo community model snapshot directory, e.g., `path/to/FramePack/hf_download/hub/models--hunyuanvideo-community--HunyuanVideo/snapshots/`. + +### Text Encoder 2 (CLIP) Model + +Choose one of the following methods: + +1. **From Comfy-Org Hugging Face repo:** Download `split_files/text_encoders/clip_l.safetensors` from [Comfy-Org/HunyuanVideo_repackaged](https://huggingface.co/Comfy-Org/HunyuanVideo_repackaged). +2. **From hunyuanvideo-community Hugging Face repo:** Download `text_encoder_2/model.safetensors` from [hunyuanvideo-community/HunyuanVideo](https://huggingface.co/hunyuanvideo-community/HunyuanVideo). +3. **From local FramePack installation:** (Same as VAE) Specify the path to the HunyuanVideo community model snapshot directory, e.g., `path/to/FramePack/hf_download/hub/models--hunyuanvideo-community--HunyuanVideo/snapshots/`. + +### Image Encoder (SigLIP) Model + +Choose one of the following methods: + +1. **From Comfy-Org Hugging Face repo:** Download `sigclip_vision_patch14_384.safetensors` from [Comfy-Org/sigclip_vision_384](https://huggingface.co/Comfy-Org/sigclip_vision_384). +2. **From lllyasviel's Hugging Face repo:** Download `image_encoder/model.safetensors` from [lllyasviel/flux_redux_bfl](https://huggingface.co/lllyasviel/flux_redux_bfl). +3. **From local FramePack installation:** If you have cloned and run the official FramePack repository, the model might be downloaded locally. Specify the path to the snapshot directory, e.g., `path/to/FramePack/hf_download/hub/models--lllyasviel--flux_redux_bfl/snapshots/`. + +
+日本語 + +※以下のページに重みが一括で公開されています(FramePack-F1を除く)。maybleMyers 氏に感謝いたします。: https://huggingface.co/maybleMyers/framepack_h1111 + +DiT、VAE、テキストエンコーダー1(LLaMA)、テキストエンコーダー2(CLIP)、および画像エンコーダー(SigLIP)モデルは複数の方法でダウンロードできます。英語の説明を参考にして、ダウンロードしてください。 + +FramePack公式のリポジトリをクローンして実行した場合、モデルはローカルにダウンロードされている可能性があります。スナップショットディレクトリへのパスを指定してください。例:`path/to/FramePack/hf_download/hub/models--lllyasviel--flux_redux_bfl/snapshots/` + +HunyuanVideoの推論をComfyUIですでに行っている場合、いくつかのモデルはすでにダウンロードされている可能性があります。 +
+ +## Pre-caching / 事前キャッシング + +The default resolution for FramePack is 640x640. See [the source code](../src/musubi_tuner/frame_pack/bucket_tools.py) for the default resolution of each bucket. + +The dataset for training must be a video dataset. Image datasets are not supported. You can train on videos of any length. Specify `frame_extraction` as `full` and set `max_frames` to a sufficiently large value. However, if the video is too long, you may run out of VRAM during VAE encoding. + +### Latent Pre-caching / latentの事前キャッシング + +Latent pre-caching uses a dedicated script for FramePack. You **must** provide the Image Encoder model. + +```bash +python src/musubi_tuner/fpack_cache_latents.py \ + --dataset_config path/to/toml \ + --vae path/to/vae_model.safetensors \ + --image_encoder path/to/image_encoder_model.safetensors \ + --vae_chunk_size 32 +``` + +Key differences from HunyuanVideo caching: +- Uses `fpack_cache_latents.py`. +- Requires the `--image_encoder` argument pointing to the downloaded SigLIP model. +- The script generates multiple cache files per video, each corresponding to a different section, with the section index appended to the filename (e.g., `..._frame_pos-0000-count_...` becomes `..._frame_pos-0000-0000-count_...`, `..._frame_pos-0000-0001-count_...`, etc.). +- Image embeddings are calculated using the Image Encoder and stored in the cache files alongside the latents. + +For VRAM savings during VAE decoding, consider using `--vae_chunk_size` and `--vae_spatial_tile_sample_min_size`. If VRAM is overflowing and using shared memory, it is recommended to set `--vae_chunk_size` to 16 or 8 to lower Conv3D chunk size. If VRAM is still an issue, consider specifying `--vae_spatial_tile_sample_min_size` to 64 or 32. This option enables tiling during VAE encoding and decoding. `--vae_tiling` option is also available to enable tiling with the default tile size of 32. + +Note that the quality may be slightly lower when using tiling. Chunking does not affect quality. + +Specifying `--f1` is required for FramePack-F1 training. For one-frame training, specify `--one_frame`. If you change the presence of these options, please overwrite the existing cache without specifying `--skip_existing`. + +`--one_frame_no_2x` and `--one_frame_no_4x` options are available for one-frame training, described in the next section. + +**FramePack-F1 support:** +You can apply the FramePack-F1 sampling method by specifying `--f1` during caching. The training script also requires specifying `--f1` to change the options during sample generation. + +By default, the sampling method used is Inverted anti-drifting (the same as during inference with the original FramePack model, using the latent and index in reverse order), described in the paper. You can switch to FramePack-F1 sampling (Vanilla sampling, using the temporally ordered latent and index) by specifying `--f1`. + +
+日本語 + +FramePackのデフォルト解像度は640x640です。各バケットのデフォルト解像度については、[ソースコード](../src/musubi_tuner/frame_pack/bucket_tools.py)を参照してください。 + +画像データセットでの学習は行えません。また動画の長さによらず学習可能です。 `frame_extraction` に `full` を指定して、`max_frames` に十分に大きな値を指定してください。ただし、あまりにも長いとVAEのencodeでVRAMが不足する可能性があります。 + +latentの事前キャッシングはFramePack専用のスクリプトを使用します。画像エンコーダーモデルを指定する必要があります。 + +HunyuanVideoのキャッシングとの主な違いは次のとおりです。 +- `fpack_cache_latents.py`を使用します。 +- ダウンロードしたSigLIPモデルを指す`--image_encoder`引数が必要です。 +- スクリプトは、各ビデオに対して複数のキャッシュファイルを生成します。各ファイルは異なるセクションに対応し、セクションインデックスがファイル名に追加されます(例:`..._frame_pos-0000-count_...`は`..._frame_pos-0000-0000-count_...`、`..._frame_pos-0000-0001-count_...`などになります)。 +- 画像埋め込みは画像エンコーダーを使用して計算され、latentとともにキャッシュファイルに保存されます。 + +VAEのdecode時のVRAM節約のために、`--vae_chunk_size`と`--vae_spatial_tile_sample_min_size`を使用することを検討してください。VRAMがあふれて共有メモリを使用している場合には、`--vae_chunk_size`を16、8などに設定してConv3Dチャンクを有効にすることをお勧めします。VRAMがまだ不足する場合は、`--vae_spatial_tile_sample_min_size`を64、32などに指定してください。このオプションはVAEのエンコードとデコード時にタイリングを有効にします。`--vae_tiling`オプションも利用可能で、デフォルトのタイルサイズ32でタイル処理を有効にします。 + +タイリングを有効にすると品質はわずかに低下する可能性があります。チャンク処理は品質に影響しません。 + +FramePack-F1の学習を行う場合は`--f1`を指定してください。これらのオプションの有無を変更する場合には、`--skip_existing`を指定せずに既存のキャッシュを上書きしてください。 + +**FramePack-F1のサポート:** +キャッシュ時のオプションに`--f1`を指定することで、FramePack-F1のサンプリング方法を適用できます。学習スクリプトについても`--f1`を指定してサンプル生成時のオプションを変更する必要があります。 + +デフォルトでは、論文のサンプリング方法 Inverted anti-drifting (無印のFramePackの推論時と同じ、逆順の latent と index を使用)を使用します。`--f1`を指定すると FramePack-F1 の Vanilla sampling (時間順の latent と index を使用)に変更できます。 +
+ +### Text Encoder Output Pre-caching / テキストエンコーダー出力の事前キャッシング + +Text encoder output pre-caching also uses a dedicated script. + +```bash +python src/musubi_tuner/fpack_cache_text_encoder_outputs.py \ + --dataset_config path/to/toml \ + --text_encoder1 path/to/text_encoder1 \ + --text_encoder2 path/to/text_encoder2 \ + --batch_size 16 +``` + +Key differences from HunyuanVideo caching: +- Uses `fpack_cache_text_encoder_outputs.py`. +- Requires both `--text_encoder1` (LLaMA) and `--text_encoder2` (CLIP) arguments. +- Uses `--fp8_llm` option to run the LLaMA Text Encoder 1 in fp8 mode for VRAM savings (similar to `--fp8_t5` in Wan2.1). +- Saves LLaMA embeddings, attention mask, and CLIP pooler output to the cache file. + +
+日本語 + +テキストエンコーダー出力の事前キャッシングも専用のスクリプトを使用します。 + +HunyuanVideoのキャッシングとの主な違いは次のとおりです。 +- `fpack_cache_text_encoder_outputs.py`を使用します。 +- LLaMAとCLIPの両方の引数が必要です。 +- LLaMAテキストエンコーダー1をfp8モードで実行するための`--fp8_llm`オプションを使用します(Wan2.1の`--fp8_t5`に似ています)。 +- LLaMAの埋め込み、アテンションマスク、CLIPのプーラー出力をキャッシュファイルに保存します。 + +
+ + +## Training / 学習 + +### Training + +Training uses a dedicated script `fpack_train_network.py`. Remember FramePack only supports I2V training. + +```bash +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 src/musubi_tuner/fpack_train_network.py \ + --dit path/to/dit_model \ + --vae path/to/vae_model.safetensors \ + --text_encoder1 path/to/text_encoder1 \ + --text_encoder2 path/to/text_encoder2 \ + --image_encoder path/to/image_encoder_model.safetensors \ + --dataset_config path/to/toml \ + --sdpa --mixed_precision bf16 \ + --optimizer_type adamw8bit --learning_rate 2e-4 --gradient_checkpointing \ + --timestep_sampling shift --weighting_scheme none --discrete_flow_shift 3.0 \ + --max_data_loader_n_workers 2 --persistent_data_loader_workers \ + --network_module networks.lora_framepack --network_dim 32 \ + --max_train_epochs 16 --save_every_n_epochs 1 --seed 42 \ + --output_dir path/to/output_dir --output_name name-of-lora +``` + +If you use the command prompt (Windows, not PowerShell), you may need to write them in a single line, or use `^` instead of `\` at the end of each line to continue the command. + +The maximum value for `--blocks_to_swap` is 36. The default resolution for FramePack is 640x640, which requires around 17GB of VRAM. If you run out of VRAM, consider lowering the dataset resolution. + +Key differences from HunyuanVideo training: +- Uses `fpack_train_network.py`. +- `--f1` option is available for FramePack-F1 model training. You need to specify the FramePack-F1 model as `--dit`. This option only changes the sample generation during training. The training process itself is the same as the original FramePack model. +- **Requires** specifying `--vae`, `--text_encoder1`, `--text_encoder2`, and `--image_encoder`. +- **Requires** specifying `--network_module networks.lora_framepack`. +- Optional `--latent_window_size` argument (default 9, should match caching). +- Memory saving options like `--fp8` (for DiT) and `--fp8_llm` (for Text Encoder 1) are available. `--fp8_scaled` is recommended when using `--fp8` for DiT. +- `--vae_chunk_size` and `--vae_spatial_tile_sample_min_size` options are available for the VAE to prevent out-of-memory during sampling (similar to caching). +- `--gradient_checkpointing` and `--gradient_checkpointing_cpu_offload` are available for memory savings. See [HunyuanVideo documentation](./hunyuan_video.md#memory-optimization) for details. +- If you encounter an error when the batch size is greater than 1 (especially when specifying `--sdpa` or `--xformers`, it will always result in an error), please specify `--split_attn`. + + +Training settings (learning rate, optimizers, etc.) are experimental. Feedback is welcome. + +
+日本語 + +FramePackの学習は専用のスクリプト`fpack_train_network.py`を使用します。FramePackはI2V学習のみをサポートしています。 + +コマンド記述例は英語版を参考にしてください。WindowsでPowerShellではなくコマンドプロンプトを使用している場合、コマンドを1行で記述するか、各行の末尾に`\`の代わりに`^`を付けてコマンドを続ける必要があります。 + +`--blocks_to_swap`の最大値は36です。FramePackのデフォルト解像度(640x640)では、17GB程度のVRAMが必要です。VRAM容量が不足する場合は、データセットの解像度を下げてください。 + +HunyuanVideoの学習との主な違いは次のとおりです。 +- `fpack_train_network.py`を使用します。 +- FramePack-F1モデルの学習時には`--f1`を指定してください。この場合、`--dit`にFramePack-F1モデルを指定する必要があります。このオプションは学習時のサンプル生成時のみに影響し、学習プロセス自体は元のFramePackモデルと同じです。 +- `--vae`、`--text_encoder1`、`--text_encoder2`、`--image_encoder`を指定する必要があります。 +- `--network_module networks.lora_framepack`を指定する必要があります。 +- 必要に応じて`--latent_window_size`引数(デフォルト9)を指定できます(キャッシング時と一致させる必要があります)。 +- `--fp8`(DiT用)や`--fp8_llm`(テキストエンコーダー1用)などのメモリ節約オプションが利用可能です。`--fp8_scaled`を使用することをお勧めします。 +- サンプル生成時にメモリ不足を防ぐため、VAE用の`--vae_chunk_size`、`--vae_spatial_tile_sample_min_size`、`--vae_tiling`オプションが利用可能です(キャッシング時と同様)。 +- メモリ節約のために`--gradient_checkpointing`が利用可能です。 +- バッチサイズが1より大きい場合にエラーが出た時には(特に`--sdpa`や`--xformers`を指定すると必ずエラーになります。)、`--split_attn`を指定してください。 + +
+ +## Inference + +Inference uses a dedicated script `fpack_generate_video.py`. + +```bash +python src/musubi_tuner/fpack_generate_video.py \ + --dit path/to/dit_model \ + --vae path/to/vae_model.safetensors \ + --text_encoder1 path/to/text_encoder1 \ + --text_encoder2 path/to/text_encoder2 \ + --image_encoder path/to/image_encoder_model.safetensors \ + --image_path path/to/start_image.jpg \ + --prompt "A cat walks on the grass, realistic style." \ + --video_size 512 768 --video_seconds 5 --fps 30 --infer_steps 25 \ + --attn_mode sdpa --fp8_scaled \ + --vae_chunk_size 32 \ + --save_path path/to/save/dir --output_type both \ + --seed 1234 --lora_multiplier 1.0 --lora_weight path/to/lora.safetensors +``` + + +Key differences from HunyuanVideo inference: +- Uses `fpack_generate_video.py`. +- `--f1` option is available for FramePack-F1 model inference (forward generation). You need to specify the FramePack-F1 model as `--dit`. +- **Requires** specifying `--vae`, `--text_encoder1`, `--text_encoder2`, and `--image_encoder`. +- **Requires** specifying `--image_path` for the starting frame. +- **Requires** specifying `--video_seconds` or `--video_sections`. `--video_seconds` specifies the length of the video in seconds, while `--video_sections` specifies the number of sections. If `--video_sections` is specified, `--video_seconds` is ignored. +- `--video_size` is the size of the generated video, height and width are specified in that order. +- `--prompt`: Prompt for generation. +- Optional `--latent_window_size` argument (default 9, should match caching and training). +- `--fp8_scaled` option is available for DiT to reduce memory usage. Quality may be slightly lower. `--fp8_llm` option is available to reduce memory usage of Text Encoder 1. `--fp8` alone is also an option for DiT but `--fp8_scaled` potentially offers better quality. +- LoRA loading options (`--lora_weight`, `--lora_multiplier`, `--include_patterns`, `--exclude_patterns`) are available. `--lycoris` is also supported. +- `--embedded_cfg_scale` (default 10.0) controls the distilled guidance scale. +- `--guidance_scale` (default 1.0) controls the standard classifier-free guidance scale. **Changing this from 1.0 is generally not recommended for the base FramePack model.** +- `--guidance_rescale` (default 0.0) is available but typically not needed. +- `--bulk_decode` option can decode all frames at once, potentially faster but uses more VRAM during decoding. `--vae_chunk_size` option is recommended to prevent out-of-memory errors. +- `--sample_solver` (default `unipc`) is available but only `unipc` is implemented. +- `--save_merged_model` option is available to save the DiT model after merging LoRA weights. Inference is skipped if this is specified. +- `--latent_paddings` option overrides the default padding for each section. Specify it as a comma-separated list of integers, e.g., `--latent_paddings 0,0,0,0`. This option is ignored if `--f1` is specified. +- `--custom_system_prompt` option overrides the default system prompt for the LLaMA Text Encoder 1. Specify it as a string. See [here](../src/musubi_tunerhunyuan_model/text_encoder.py#L152) for the default system prompt. +- `--rope_scaling_timestep_threshold` option is the RoPE scaling timestep threshold, default is None (disabled). If set, RoPE scaling is applied only when the timestep exceeds the threshold. Start with around 800 and adjust as needed. This option is intended for one-frame inference and may not be suitable for other cases. +- `--rope_scaling_factor` option is the RoPE scaling factor, default is 0.5, assuming a resolution of 2x. For 1.5x resolution, around 0.7 is recommended. + +Other options like `--video_size`, `--fps`, `--infer_steps`, `--save_path`, `--output_type`, `--seed`, `--attn_mode`, `--blocks_to_swap`, `--vae_chunk_size`, `--vae_spatial_tile_sample_min_size` function similarly to HunyuanVideo/Wan2.1 where applicable. `--vae_tiling` option is also available. + +`--output_type` supports `latent_images` in addition to the options available in HunyuanVideo/Wan2.1. This option saves the latent and image files in the specified directory. + +The LoRA weights that can be specified in `--lora_weight` are not limited to the FramePack weights trained in this repository. You can also specify the HunyuanVideo LoRA weights from this repository and the HunyuanVideo LoRA weights from diffusion-pipe (automatic detection). + +The maximum value for `--blocks_to_swap` is 38. + +
+日本語 + +FramePackの推論は専用のスクリプト`fpack_generate_video.py`を使用します。コマンド記述例は英語版を参考にしてください。 + +HunyuanVideoの推論との主な違いは次のとおりです。 +- `fpack_generate_video.py`を使用します。 +- `--f1`を指定すると、FramePack-F1モデルの推論を行います(順方向で生成)。`--dit`にFramePack-F1モデルを指定する必要があります。 +- `--vae`、`--text_encoder1`、`--text_encoder2`、`--image_encoder`を指定する必要があります。 +- `--image_path`を指定する必要があります(開始フレーム)。 +- `--video_seconds` または `--video_sections` を指定する必要があります。`--video_seconds`は秒単位でのビデオの長さを指定し、`--video_sections`はセクション数を指定します。`--video_sections`を指定した場合、`--video_seconds`は無視されます。 +- `--video_size`は生成するビデオのサイズで、高さと幅をその順番で指定します。 +- `--prompt`: 生成用のプロンプトです。 +- 必要に応じて`--latent_window_size`引数(デフォルト9)を指定できます(キャッシング時、学習時と一致させる必要があります)。 +- DiTのメモリ使用量を削減するために、`--fp8_scaled`オプションを指定可能です。品質はやや低下する可能性があります。またText Encoder 1のメモリ使用量を削減するために、`--fp8_llm`オプションを指定可能です。DiT用に`--fp8`単独のオプションも用意されていますが、`--fp8_scaled`の方が品質が良い可能性があります。 +- LoRAの読み込みオプション(`--lora_weight`、`--lora_multiplier`、`--include_patterns`、`--exclude_patterns`)が利用可能です。LyCORISもサポートされています。 +- `--embedded_cfg_scale`(デフォルト10.0)は、蒸留されたガイダンススケールを制御します。通常は変更しないでください。 +- `--guidance_scale`(デフォルト1.0)は、標準の分類器フリーガイダンススケールを制御します。**FramePackモデルのベースモデルでは、通常1.0から変更しないことをお勧めします。** +- `--guidance_rescale`(デフォルト0.0)も利用可能ですが、通常は必要ありません。 +- `--bulk_decode`オプションは、すべてのフレームを一度にデコードできるオプションです。高速ですが、デコード中にVRAMを多く使用します。VRAM不足エラーを防ぐために、`--vae_chunk_size`オプションを指定することをお勧めします。 +- `--sample_solver`(デフォルト`unipc`)は利用可能ですが、`unipc`のみが実装されています。 +- `--save_merged_model`オプションは、LoRAの重みをマージした後にDiTモデルを保存するためのオプションです。これを指定すると推論はスキップされます。 +- `--latent_paddings`オプションは、各セクションのデフォルトのパディングを上書きします。カンマ区切りの整数リストとして指定します。例:`--latent_paddings 0,0,0,0`。`--f1`を指定した場合は無視されます。 +- `--custom_system_prompt`オプションは、LLaMA Text Encoder 1のデフォルトのシステムプロンプトを上書きします。文字列として指定します。デフォルトのシステムプロンプトは[こちら](../src/musubi_tuner/hunyuan_model/text_encoder.py#L152)を参照してください。 +- `--rope_scaling_timestep_threshold`オプションはRoPEスケーリングのタイムステップ閾値で、デフォルトはNone(無効)です。設定すると、タイムステップが閾値以上の場合にのみRoPEスケーリングが適用されます。800程度から初めて調整してください。1フレーム推論時での使用を想定しており、それ以外の場合は想定していません。 +- `--rope_scaling_factor`オプションはRoPEスケーリング係数で、デフォルトは0.5で、解像度が2倍の場合を想定しています。1.5倍なら0.7程度が良いでしょう。 + +`--video_size`、`--fps`、`--infer_steps`、`--save_path`、`--output_type`、`--seed`、`--attn_mode`、`--blocks_to_swap`、`--vae_chunk_size`、`--vae_spatial_tile_sample_min_size`などの他のオプションは、HunyuanVideo/Wan2.1と同様に機能します。また`--vae_tiling`オプションも利用可能です。 + +`--output_type`はHunyuanVideo/Wan2.1で利用可能なオプションに加えて、`latent_images`をサポートしています。このオプションは、指定されたディレクトリにlatentと画像ファイルを保存します。 + +`--lora_weight`に指定できるLoRAの重みは、当リポジトリで学習したFramePackの重み以外に、当リポジトリのHunyuanVideoのLoRA、diffusion-pipeのHunyuanVideoのLoRAが指定可能です(自動判定)。 + +`--blocks_to_swap`の最大値は38です。 +
+ +## Batch and Interactive Modes / バッチモードとインタラクティブモード + +In addition to single video generation, FramePack now supports batch generation from file and interactive prompt input: + +### Batch Mode from File / ファイルからのバッチモード + +Generate multiple videos from prompts stored in a text file: + +```bash +python src/musubi_tuner/fpack_generate_video.py --from_file prompts.txt +--dit path/to/dit_model --vae path/to/vae_model.safetensors +--text_encoder1 path/to/text_encoder1 --text_encoder2 path/to/text_encoder2 +--image_encoder path/to/image_encoder_model.safetensors --save_path output_directory +``` + +The prompts file format: +- One prompt per line +- Empty lines and lines starting with # are ignored (comments) +- Each line can include prompt-specific parameters using command-line style format: + +``` +A beautiful sunset over mountains --w 832 --h 480 --f 5 --d 42 --s 20 --i path/to/start_image.jpg +A busy city street at night --w 480 --h 832 --i path/to/another_start.jpg +``` + +Supported inline parameters (if omitted, default values from the command line are used): +- `--w`: Width +- `--h`: Height +- `--f`: Video seconds +- `--d`: Seed +- `--s`: Inference steps +- `--g` or `--l`: Guidance scale +- `--i`: Image path (for start image) +- `--im`: Image mask path +- `--n`: Negative prompt +- `--vs`: Video sections +- `--ei`: End image path +- `--ci`: Control image path (explained in one-frame inference documentation) +- `--cim`: Control image mask path (explained in one-frame inference documentation) +- `--of`: One frame inference mode options (same as `--one_frame_inference` in the command line), options for one-frame inference + +In batch mode, models are loaded once and reused for all prompts, significantly improving overall generation time compared to multiple single runs. + +### Interactive Mode / インタラクティブモード + +Interactive command-line interface for entering prompts: + +```bash +python src/musubi_tuner/fpack_generate_video.py --interactive +--dit path/to/dit_model --vae path/to/vae_model.safetensors +--text_encoder1 path/to/text_encoder1 --text_encoder2 path/to/text_encoder2 +--image_encoder path/to/image_encoder_model.safetensors --save_path output_directory +``` + +In interactive mode: +- Enter prompts directly at the command line +- Use the same inline parameter format as batch mode +- Use Ctrl+D (or Ctrl+Z on Windows) to exit +- Models remain loaded between generations for efficiency + +
+日本語 + +単一動画の生成に加えて、FramePackは現在、ファイルからのバッチ生成とインタラクティブなプロンプト入力をサポートしています。 + +#### ファイルからのバッチモード + +テキストファイルに保存されたプロンプトから複数の動画を生成します: + +```bash +python src/musubi_tuner/fpack_generate_video.py --from_file prompts.txt +--dit path/to/dit_model --vae path/to/vae_model.safetensors +--text_encoder1 path/to/text_encoder1 --text_encoder2 path/to/text_encoder2 +--image_encoder path/to/image_encoder_model.safetensors --save_path output_directory +``` + +プロンプトファイルの形式(サンプルは英語ドキュメントを参照): +- 1行に1つのプロンプト +- 空行や#で始まる行は無視されます(コメント) +- 各行にはコマンドライン形式でプロンプト固有のパラメータを含めることができます: + +サポートされているインラインパラメータ(省略した場合、コマンドラインのデフォルト値が使用されます) +- `--w`: 幅 +- `--h`: 高さ +- `--f`: 動画の秒数 +- `--d`: シード +- `--s`: 推論ステップ +- `--g` または `--l`: ガイダンススケール +- `--i`: 画像パス(開始画像用) +- `--im`: 画像マスクパス +- `--n`: ネガティブプロンプト +- `--vs`: 動画セクション数 +- `--ei`: 終了画像パス +- `--ci`: 制御画像パス(1フレーム推論のドキュメントで解説) +- `--cim`: 制御画像マスクパス(1フレーム推論のドキュメントで解説) +- `--of`: 1フレーム推論モードオプション(コマンドラインの`--one_frame_inference`と同様、1フレーム推論のオプション) + +バッチモードでは、モデルは一度だけロードされ、すべてのプロンプトで再利用されるため、複数回の単一実行と比較して全体的な生成時間が大幅に改善されます。 + +#### インタラクティブモード + +プロンプトを入力するためのインタラクティブなコマンドラインインターフェース: + +```bash +python src/musubi_tuner/fpack_generate_video.py --interactive +--dit path/to/dit_model --vae path/to/vae_model.safetensors +--text_encoder1 path/to/text_encoder1 --text_encoder2 path/to/text_encoder2 +--image_encoder path/to/image_encoder_model.safetensors --save_path output_directory +``` + +インタラクティブモードでは: +- コマンドラインで直接プロンプトを入力 +- バッチモードと同じインラインパラメータ形式を使用 +- 終了するには Ctrl+D (Windowsでは Ctrl+Z) を使用 +- 効率のため、モデルは生成間で読み込まれたままになります +
+ +## Advanced Video Control Features (Experimental) / 高度なビデオ制御機能(実験的) + +This section describes experimental features added to the `fpack_generate_video.py` script to provide finer control over the generated video content, particularly useful for longer videos or sequences requiring specific transitions or states. These features leverage the Inverted Anti-drifting sampling method inherent to FramePack. + +### **1. End Image Guidance (`--end_image_path`)** + +* **Functionality:** Guides the generation process to make the final frame(s) of the video resemble a specified target image. +* **Usage:** `--end_image_path ` +* **Mechanism:** The provided image is encoded using the VAE. This latent representation is used as a target or starting point during the generation of the final video section (which is the first step in Inverted Anti-drifting). +* **Use Cases:** Defining a clear ending for the video, such as a character striking a specific pose or a product appearing in a close-up. + +This option is ignored if `--f1` is specified. The end image is not used in the FramePack-F1 model. + +### **2. Section Start Image Guidance (`--image_path` Extended Format)** + +* **Functionality:** Guides specific sections within the video to start with a visual state close to a provided image. + * You can force the start image by setting `--latent_paddings` to `0,0,0,0` (specify the number of sections as a comma-separated list). If `latent_paddings` is set to 1 or more, the specified image will be used as a reference image (default behavior). +* **Usage:** `--image_path "SECTION_SPEC:path/to/image.jpg;;;SECTION_SPEC:path/to/another.jpg;;;..."` + * `SECTION_SPEC`: Defines the target section(s). Rules: + * `0`: The first section of the video (generated last in Inverted Anti-drifting). + * `-1`: The last section of the video (generated first). + * `N` (non-negative integer): The N-th section (0-indexed). + * `-N` (negative integer): The N-th section from the end. + * `S-E` (range, e.g., `0-2`): Applies the same image guidance to sections S through E (inclusive). + * Use `;;;` as a separator between definitions. + * If no image is specified for a section, generation proceeds based on the prompt and preceding (future time) section context. +* **Mechanism:** When generating a specific section, if a corresponding start image is provided, its VAE latent representation is strongly referenced as the "initial state" for that section. This guides the beginning of the section towards the specified image while attempting to maintain temporal consistency with the subsequent (already generated) section. +* **Use Cases:** Defining clear starting points for scene changes, specifying character poses or attire at the beginning of certain sections. + +### **3. Section-Specific Prompts (`--prompt` Extended Format)** + +* **Functionality:** Allows providing different text prompts for different sections of the video, enabling more granular control over the narrative or action flow. +* **Usage:** `--prompt "SECTION_SPEC:Prompt text for section(s);;;SECTION_SPEC:Another prompt;;;..."` + * `SECTION_SPEC`: Uses the same rules as `--image_path`. + * Use `;;;` as a separator. + * If a prompt for a specific section is not provided, the prompt associated with index `0` (or the closest specified applicable prompt) is typically used. Check behavior if defaults are critical. +* **Mechanism:** During the generation of each section, the corresponding section-specific prompt is used as the primary textual guidance for the model. +* **Prompt Content Recommendation** when using `--latent_paddings 0,0,0,0` without `--f1` (original FramePack model): + * Recall that FramePack uses Inverted Anti-drifting and references future context. + * It is recommended to describe "**the main content or state change that should occur in the current section, *and* the subsequent events or states leading towards the end of the video**" in the prompt for each section. + * Including the content of subsequent sections in the current section's prompt helps the model maintain context and overall coherence. + * Example: For section 1, the prompt might describe what happens in section 1 *and* briefly summarize section 2 (and beyond). + * However, based on observations (e.g., the `latent_paddings` comment), the model's ability to perfectly utilize very long-term context might be limited. Experimentation is key. Describing just the "goal for the current section" might also work. Start by trying the "section and onwards" approach. +* Use the default prompt when `latent_paddings` is >= 1 or `--latent_paddings` is not specified, or when using `--f1` (FramePack-F1 model). +* **Use Cases:** Describing evolving storylines, gradual changes in character actions or emotions, step-by-step processes over time. + +### **Combined Usage Example** (with `--f1` not specified) + +Generating a 3-section video of "A dog runs towards a thrown ball, catches it, and runs back": + +```bash +python src/musubi_tuner/fpack_generate_video.py \ + --prompt "0:A dog runs towards a thrown ball, catches it, and runs back;;;1:The dog catches the ball and then runs back towards the viewer;;;2:The dog runs back towards the viewer holding the ball" \ + --image_path "0:./img_start_running.png;;;1:./img_catching.png;;;2:./img_running_back.png" \ + --end_image_path ./img_returned.png \ + --save_path ./output \ + # ... other arguments +``` + +* **Generation Order:** Section 2 -> Section 1 -> Section 0 +* **Generating Section 2:** + * Prompt: "The dog runs back towards the viewer holding the ball" + * Start Image: `./img_running_back.png` + * End Image: `./img_returned.png` (Initial target) +* **Generating Section 1:** + * Prompt: "The dog catches the ball and then runs back towards the viewer" + * Start Image: `./img_catching.png` + * Future Context: Generated Section 2 latent +* **Generating Section 0:** + * Prompt: "A dog runs towards a thrown ball, catches it, and runs back" + * Start Image: `./img_start_running.png` + * Future Context: Generated Section 1 & 2 latents + +### **Important Considerations** + +* **Inverted Generation:** Always remember that generation proceeds from the end of the video towards the beginning. Section `-1` (the last section, `2` in the example) is generated first. +* **Continuity vs. Guidance:** While start image guidance is powerful, drastically different images between sections might lead to unnatural transitions. Balance guidance strength with the need for smooth flow. +* **Prompt Optimization:** The prompt content recommendation is a starting point. Fine-tune prompts based on observed model behavior and desired output quality. + +
+日本語 + +### **高度な動画制御機能(実験的)** + +このセクションでは、`fpack_generate_video.py` スクリプトに追加された実験的な機能について説明します。これらの機能は、生成される動画の内容をより詳細に制御するためのもので、特に長い動画や特定の遷移・状態が必要なシーケンスに役立ちます。これらの機能は、FramePack固有のInverted Anti-driftingサンプリング方式を活用しています。 + +#### **1. 終端画像ガイダンス (`--end_image_path`)** + +* **機能:** 動画の最後のフレーム(群)を指定したターゲット画像に近づけるように生成を誘導します。 +* **書式:** `--end_image_path <画像ファイルパス>` +* **動作:** 指定された画像はVAEでエンコードされ、その潜在表現が動画の最終セクション(Inverted Anti-driftingでは最初に生成される)の生成時の目標または開始点として使用されます。 +* **用途:** キャラクターが特定のポーズで終わる、特定の商品がクローズアップで終わるなど、動画の結末を明確に定義する場合。 + +このオプションは、`--f1`を指定した場合は無視されます。FramePack-F1モデルでは終端画像は使用されません。 + +#### **2. セクション開始画像ガイダンス (`--image_path` 拡張書式)** + +* **機能:** 動画内の特定のセクションが、指定された画像に近い視覚状態から始まるように誘導します。 + * `--latent_paddings`を`0,0,0,0`(カンマ区切りでセクション数だけ指定)に設定することで、セクションの開始画像を強制できます。`latent_paddings`が1以上の場合、指定された画像は参照画像として使用されます。 +* **書式:** `--image_path "セクション指定子:画像パス;;;セクション指定子:別の画像パス;;;..."` + * `セクション指定子`: 対象セクションを定義します。ルール: + * `0`: 動画の最初のセクション(Inverted Anti-driftingでは最後に生成)。 + * `-1`: 動画の最後のセクション(最初に生成)。 + * `N`(非負整数): N番目のセクション(0始まり)。 + * `-N`(負整数): 最後からN番目のセクション。 + * `S-E`(範囲, 例:`0-2`): セクションSからE(両端含む)に同じ画像を適用。 + * 区切り文字は `;;;` です。 + * セクションに画像が指定されていない場合、プロンプトと後続(未来時刻)セクションのコンテキストに基づいて生成されます。 +* **動作:** 特定セクションの生成時、対応する開始画像が指定されていれば、そのVAE潜在表現がそのセクションの「初期状態」として強く参照されます。これにより、後続(生成済み)セクションとの時間的連続性を維持しようとしつつ、セクションの始まりを指定画像に近づけます。 +* **用途:** シーン変更の起点を明確にする、特定のセクション開始時のキャラクターのポーズや服装を指定するなど。 + +#### **3. セクション別プロンプト (`--prompt` 拡張書式)** + +* **機能:** 動画のセクションごとに異なるテキストプロンプトを与え、物語やアクションの流れをより細かく指示できます。 +* **書式:** `--prompt "セクション指定子:プロンプトテキスト;;;セクション指定子:別のプロンプト;;;..."` + * `セクション指定子`: `--image_path` と同じルールです。 + * 区切り文字は `;;;` です。 + * 特定セクションのプロンプトがない場合、通常はインデックス`0`に関連付けられたプロンプト(または最も近い適用可能な指定プロンプト)が使用されます。デフォルトの挙動が重要な場合は確認してください。 +* **動作:** 各セクションの生成時、対応するセクション別プロンプトがモデルへの主要なテキスト指示として使用されます。 +* `latent_paddings`に`0`を指定した場合(非F1モデル)の **プロンプト内容の推奨:** + * FramePackはInverted Anti-driftingを採用し、未来のコンテキストを参照することを思い出してください。 + * 各セクションのプロンプトには、「**現在のセクションで起こるべき主要な内容や状態変化、*および*それに続く動画の終端までの内容**」を記述することを推奨します。 + * 現在のセクションのプロンプトに後続セクションの内容を含めることで、モデルが全体的な文脈を把握し、一貫性を保つのに役立ちます。 + * 例:セクション1のプロンプトには、セクション1の内容 *と* セクション2の簡単な要約を記述します。 + * ただし、モデルの長期コンテキスト完全利用能力には限界がある可能性も示唆されています(例:`latent_paddings`コメント)。実験が鍵となります。「現在のセクションの目標」のみを記述するだけでも機能する場合があります。まずは「セクションと以降」アプローチを試すことをお勧めします。 +* 使用するプロンプトは、`latent_paddings`が`1`以上または指定されていない場合、または`--f1`(FramePack-F1モデル)を使用している場合は、通常のプロンプト内容を記述してください。 +* **用途:** 時間経過に伴うストーリーの変化、キャラクターの行動や感情の段階的な変化、段階的なプロセスなどを記述する場合。 + +#### **組み合わせ使用例** (`--f1`未指定時) + +「投げられたボールに向かって犬が走り、それを捕まえ、走って戻ってくる」3セクション動画の生成: +(コマンド記述例は英語版を参考にしてください) + +* **生成順序:** セクション2 → セクション1 → セクション0 +* **セクション2生成時:** + * プロンプト: "犬がボールを咥えてこちらに向かって走ってくる" + * 開始画像: `./img_running_back.png` + * 終端画像: `./img_returned.png` (初期目標) +* **セクション1生成時:** + * プロンプト: "犬がボールを捕まえ、その後こちらに向かって走ってくる" + * 開始画像: `./img_catching.png` + * 未来コンテキスト: 生成済みセクション2の潜在表現 +* **セクション0生成時:** + * プロンプト: "犬が投げられたボールに向かって走り、それを捕まえ、走って戻ってくる" + * 開始画像: `./img_start_running.png` + * 未来コンテキスト: 生成済みセクション1 & 2の潜在表現 + +#### **重要な考慮事項** + +* **逆順生成:** 生成は動画の終わりから始まりに向かって進むことを常に意識してください。セクション`-1`(最後のセクション、上の例では `2`)が最初に生成されます。 +* **連続性とガイダンスのバランス:** 開始画像ガイダンスは強力ですが、セクション間で画像が大きく異なると、遷移が不自然になる可能性があります。ガイダンスの強さとスムーズな流れの必要性のバランスを取ってください。 +* **プロンプトの最適化:** 推奨されるプロンプト内容はあくまでも参考です。モデルの観察された挙動と望ましい出力品質に基づいてプロンプトを微調整してください。 + +
diff --git a/VRGDG_Musubi-tuner/docs/framepack_1f.md b/VRGDG_Musubi-tuner/docs/framepack_1f.md new file mode 100644 index 0000000000000000000000000000000000000000..0fc6ac8b74268c4879c84fc22c4a55e9adffa689 --- /dev/null +++ b/VRGDG_Musubi-tuner/docs/framepack_1f.md @@ -0,0 +1,367 @@ +# FramePack One Frame (Single Frame) Inference and Training / FramePack 1フレーム推論と学習 + +## Overview / 概要 + +This document explains advanced inference and training methods using the FramePack model, particularly focusing on **"1-frame inference"** and its extensions. These features aim to leverage FramePack's flexibility to enable diverse image generation and editing tasks beyond simple video generation. + +### The Concept and Development of 1-Frame Inference + +While FramePack is originally a model for generating sequential video frames (or frame sections), it was discovered that by focusing on its internal structure, particularly how it handles temporal information with RoPE (Rotary Position Embedding), interesting control over single-frame generation is possible. + +1. **Basic 1-Frame Inference**: + * It takes an initial image and a prompt as input, limiting the number of generated frames to just one. + * In this process, by intentionally setting a large RoPE timestamp (`target_index`) for the single frame to be generated, a single static image can be obtained that reflects temporal and semantic changes from the initial image according to the prompt. + * This utilizes FramePack's characteristic of being highly sensitive to RoPE timestamps, as it supports bidirectional contexts like "Inverted anti-drifting." This allows for operations similar to natural language-based image editing, albeit in a limited capacity, without requiring additional training. + +2. **Kisekaeichi Method (Feature Merging via Post-Reference)**: + * This method, an extension of basic 1-frame inference, was **proposed by furusu**. In addition to the initial image, it also uses a reference image corresponding to a "next section-start image" (treated as `clean_latent_post`) as input. + * The RoPE timestamp (`target_index`) for the image to be generated is set to an intermediate value between the timestamps of the initial image and the section-end image. + * More importantly, masking (e.g., zeroing out specific regions) is applied to the latent representation of each reference image. For example, by setting masks to extract a character's face and body shape from the initial image and clothing textures from the reference image, an image can be generated that fuses the desired features of both, similar to a character "dress-up" or outfit swapping. This method can also be fundamentally achieved without additional training. + +3. **1f-mc (one frame multi-control) Method (Proximal Frame Blending)**: + * This method was **proposed by mattyamonaca**. It takes two reference images as input: an initial image (e.g., at `t=0`) and a subsequent image (e.g., at `t=1`, the first frame of a section), and generates a single image blending their features. + * Unlike Kisekaeichi, latent masking is typically not performed. + * To fully leverage this method, additional training using LoRA (Low-Rank Adaptation) is recommended. Through training, the model can better learn the relationship and blending method between the two input images to achieve specific editing effects. + +### Integration into a Generalized Control Framework + +The concepts utilized in the methods above—specifying reference images, manipulating timestamps, and applying latent masks—have been generalized to create a more flexible control framework. +Users can arbitrarily specify the following elements for both inference and LoRA training: + +* **Control Images**: Any set of input images intended to influence the model. +* **Clean Latent Index (Indices)**: Timestamps corresponding to each control image. These are treated as `clean latent index` internally by FramePack and can be set to any position on the time axis. This is specified as `control_index`. +* **Latent Masks**: Masks applied to the latent representation of each control image, allowing selective control over which features from the control images are utilized. This is specified as `control_image_mask_path` or the alpha channel of the control image. +* **Target Index**: The timestamp for the single frame to be generated. + +This generalized control framework, along with corresponding extensions to the inference and LoRA training tools, has enabled advanced applications such as: + +* Development of LoRAs that stabilize 1-frame inference effects (e.g., a camera orbiting effect) that were previously unstable with prompts alone. +* Development of Kisekaeichi LoRAs that learn to perform desired feature merging under specific conditions (e.g., ignoring character information from a clothing reference image), thereby automating the masking process through learning. + +These features maximize FramePack's potential and open up new creative possibilities in static image generation and editing. Subsequent sections will detail the specific options for utilizing these functionalities. + +
+日本語 + +このドキュメントでは、FramePackモデルを用いた高度な推論および学習手法、特に「1フレーム推論」とその拡張機能について解説します。これらの機能は、FramePackの柔軟性を活かし、動画生成に留まらない多様な画像生成・編集タスクを実現することを目的としています。 + +### 1フレーム推論の発想と発展 + +FramePackは本来、連続する動画フレーム(またはフレームセクション)を生成するモデルですが、その内部構造、特に時間情報を扱うRoPE (Rotary Position Embedding) の扱いに着目することで、単一フレームの生成においても興味深い制御が可能になることが発見されました。 + +1. **基本的な1フレーム推論**: + * 開始画像とプロンプトを入力とし、生成するフレーム数を1フレームに限定します。 + * この際、生成する1フレームに割り当てるRoPEのタイムスタンプ(`target_index`)を意図的に大きな値に設定することで、開始画像からプロンプトに従って時間的・意味的に変化した単一の静止画を得ることができます。 + * これは、FramePackがInverted anti-driftingなどの双方向コンテキストに対応するため、RoPEのタイムスタンプに対して敏感に反応する特性を利用したものです。これにより、学習なしで限定的ながら自然言語による画像編集に近い操作が可能です。 + +2. **kisekaeichi方式 (ポスト参照による特徴マージ)**: + * 基本的な1フレーム推論を発展させたこの方式は、**furusu氏により提案されました**。開始画像に加え、「次のセクションの開始画像」に相当する参照画像(`clean_latent_post`として扱われる)も入力として利用します。 + * 生成する画像のRoPEタイムスタンプ(`target_index`)を、開始画像のタイムスタンプとセクション終端画像のタイムスタンプの中間的な値に設定します。 + * さらに重要な点として、各参照画像のlatent表現に対してマスク処理(特定領域を0で埋めるなど)を施します。例えば、開始画像からはキャラクターの顔や体型を、参照画像からは服装のテクスチャを抽出するようにマスクを設定することで、キャラクターの「着せ替え」のような、両者の望ましい特徴を融合させた画像を生成できます。この手法も基本的には学習不要で実現可能です。 + +3. **1f-mc (one frame multi-control) 方式 (近接フレームブレンド)**: + * この方式は、**mattyamonaca氏により提案されました**。開始画像(例: `t=0`)と、その直後の画像(例: `t=1`、セクションの最初のフレーム)の2つを参照画像として入力し、それらの特徴をブレンドした単一画像を生成します。 + * kisekaeichiとは異なり、latentマスクは通常行いません。 + * この方式の真価を発揮するには、LoRA (Low-Rank Adaptation) による追加学習が推奨されます。学習により、モデルは2つの入力画像間の関係性やブレンド方法をより適切に学習し、特定の編集効果を実現できます。 + +### 汎用的な制御フレームワークへの統合 + +上記の各手法で利用されていた「参照画像の指定」「タイムスタンプの操作」「latentマスクの適用」といった概念を一般化し、より柔軟な制御を可能にするための拡張が行われました。 +ユーザーは以下の要素を任意に指定して、推論およびLoRA学習を行うことができます。 + +* **制御画像 (Control Images)**: モデルに影響を与えるための任意の入力画像群。 +* **Clean Latent Index (Indices)**: 各制御画像に対応するタイムスタンプ。FramePack内部の`clean latent index`として扱われ、時間軸上の任意の位置を指定可能です。`control_index`として指定します。 +* **Latentマスク (Latent Masks)**: 各制御画像のlatentに適用するマスク。これにより、制御画像から利用する特徴を選択的に制御します。`control_image_mask_path`または制御画像のアルファチャンネルとして指定します。 +* **Target Index**: 生成したい単一フレームのタイムスタンプ。 + +この汎用的な制御フレームワークと、それに対応した推論ツールおよびLoRA学習ツールの拡張により、以下のような高度な応用が可能になりました。 + +* プロンプトだけでは不安定だった1フレーム推論の効果(例: カメラ旋回)を安定化させるLoRAの開発。 +* マスク処理を手動で行う代わりに、特定の条件下(例: 服の参照画像からキャラクター情報を無視する)で望ましい特徴マージを行うように学習させたkisekaeichi LoRAの開発。 + +これらの機能は、FramePackのポテンシャルを最大限に引き出し、静止画生成・編集における新たな創造の可能性を拓くものです。以降のセクションでは、これらの機能を実際に利用するための具体的なオプションについて説明します。 + +
+ +## One Frame (Single Frame) Training / 1フレーム学習 + +**This feature is experimental.** It trains in the same way as one frame inference. + +The dataset must be an image dataset. If you use caption files, you need to specify `control_directory` and place the **start images** in that directory. The `image_directory` should contain the images after the change. The filenames of both directories must match. Caption files should be placed in the `image_directory`. + +If you use JSONL files, specify them as `{"image_path": "/path/to/target_image1.jpg", "control_path": "/path/to/source_image1.jpg", "caption": "The object changes to red."}`. The `image_path` should point to the images after the change, and `control_path` should point to the starting images. + +For the dataset configuration, see [here](./dataset_config.md#sample-for-image-dataset-with-control-images) and [here](./dataset_config.md#framepack-one-frame-training). There are also examples for kisekaeichi and 1f-mc settings. + +For single frame training, specify `--one_frame` in `fpack_cache_latents.py` to create the cache. You can also use `--one_frame_no_2x` and `--one_frame_no_4x` options, which have the same meaning as `no_2x` and `no_4x` during inference. It is recommended to set these options to match the inference settings. + +If you change whether to use one frame training or these options, please overwrite the existing cache without specifying `--skip_existing`. + +Specify `--one_frame` in `fpack_train_network.py` to change the inference method during sample generation. + +The optimal training settings are currently unknown. Feedback is welcome. + +### Example of prompt file description for sample generation + +The command line options `--one_frame_inference` corresponds to `--of`, and `--control_image_path` corresponds to `--ci`. + +Note that `--ci` can be specified multiple times, but `--control_image_path` is specified as `--control_image_path img1.png img2.png`, while `--ci` is specified as `--ci img1.png --ci img2.png`. + +Normal single frame training: +``` +The girl wears a school uniform. --i path/to/start.png --ci path/to/start.png --of no_2x,no_4x,target_index=1,control_index=0 --d 1111 --f 1 --s 10 --fs 7 --d 1234 --w 384 --h 576 +``` + +Kisekaeichi training: +``` +The girl wears a school uniform. --i path/to/start_with_alpha.png --ci path/to/ref_with_alpha.png --ci path/to/start_with_alpha.png --of no_post,no_2x,no_4x,target_index=5,control_index=0;10 --d 1111 --f 1 --s 10 --fs 7 --d 1234 --w 384 --h 576 +``` + +
+日本語 + +**この機能は実験的なものです。** 1フレーム推論と同様の方法で学習を行います。 + +データセットは画像データセットである必要があります。キャプションファイルを用いる場合は、`control_directory`を追加で指定し、そのディレクトリに**開始画像**を格納してください。`image_directory`には変化後の画像を格納します。両者のファイル名は一致させる必要があります。キャプションファイルは`image_directory`に格納してください。 + +JSONLファイルを用いる場合は、`{"image_path": "/path/to/target_image1.jpg", "control_path": "/path/to/source_image1.jpg", "caption": "The object changes to red"}`のように指定してください。`image_path`は変化後の画像、`control_path`は開始画像を指定します。 + +データセットの設定については、[こちら](./dataset_config.md#sample-for-image-dataset-with-control-images)と[こちら](./dataset_config.md#framepack-one-frame-training)も参照してください。kisekaeichiと1f-mcの設定例もそちらにあります。 + +1フレーム学習時は、`fpack_cache_latents.py`に`--one_frame`を指定してキャッシュを作成してください。また`--one_frame_no_2x`と`--one_frame_no_4x`オプションも利用可能です。推論時の`no_2x`、`no_4x`と同じ意味を持ちますので、推論時と同じ設定にすることをお勧めします。 + +1フレーム学習か否かを変更する場合、またこれらのオプションを変更する場合は、`--skip_existing`を指定せずに既存のキャッシュを上書きしてください。 + +また、`fpack_train_network.py`に`--one_frame`を指定してサンプル画像生成時の推論方法を変更してください。 + +最適な学習設定は今のところ不明です。フィードバックを歓迎します。 + +**サンプル生成のプロンプトファイル記述例** + +コマンドラインオプション`--one_frame_inference`に相当する `--of`と、`--control_image_path`に相当する`--ci`が用意されています。 + +※ `--ci`は複数指定可能ですが、`--control_image_path`は`--control_image_path img1.png img2.png`のようにスペースで区切るのに対して、`--ci`は`--ci img1.png --ci img2.png`のように指定するので注意してください。 + +通常の1フレーム学習: +``` +The girl wears a school uniform. --i path/to/start.png --ci path/to/start.png --of no_2x,no_4x,target_index=1,control_index=0 --d 1111 --f 1 --s 10 --fs 7 --d 1234 --w 384 --h 576 +``` + +kisekaeichi方式: +``` +The girl wears a school uniform. --i path/to/start_with_alpha.png --ci path/to/ref_with_alpha.png --ci path/to/start_with_alpha.png --of no_post,no_2x,no_4x,target_index=5,control_index=0;10 --d 1111 --f 1 --s 10 --fs 7 --d 1234 --w 384 --h 576 +``` + +
+ +## One (single) Frame Inference / 1フレーム推論 + +**This feature is highly experimental** and not officially supported. It is intended for users who want to explore the potential of FramePack for one frame inference, which is not a standard feature of the model. + +This script also allows for one frame inference, which is not an official feature of FramePack but rather a custom implementation. + +Theoretically, it generates an image after a specified time from the starting image, following the prompt. This means that, although limited, it allows for natural language-based image editing. + +To perform one frame inference, specify some option in the `--one_frame_inference` option. Here is an example: + +```bash +--video_sections 1 --output_type latent_images --one_frame_inference default --image_path start_image.png --control_image_path start_image.png +``` + +The `--image_path` is used to obtain the SIGCLIP features for one frame inference. Normally, you should specify the starting image. The `--control_image_path` is newly used to specify the control image, but for normal one frame inference, you should also specify the starting image. + +The `--one_frame_inference` option is recommended to be set to `default` or `no_2x,no_4x`. If you specify `--output_type` as `latent_images`, both the latent and image will be saved. + +You can specify the following strings in the `--one_frame_inference` option, separated by commas: + +- `no_2x`: Generates without passing clean latents 2x with zero vectors to the model. Slightly improves generation speed. The impact on generation results is unknown. +- `no_4x`: Generates without passing clean latents 4x with zero vectors to the model. Slightly improves generation speed. The impact on generation results is unknown. +- `no_post`: Generates without passing clean latents post with zero vectors to the model. Improves generation speed by about 20%, but may result in unstable generation. +- `target_index=`: Specifies the index of the image to be generated. The default is the last frame (i.e., `latent_window_size`). + +For example, you can use `--one_frame_inference default` to pass clean latents 2x, clean latents 4x, and post to the model. `--one_frame_inference no_2x,no_4x` if you want to skip passing clean latents 2x and 4x to the model. `--one_frame_inference target_index=9` can be used to specify the target index for the generated image. + +The `--one_frame_inference` option also supports advanced inference, which is described in the next section. This option allows for more detailed control using additional parameters like `target_index` and `control_index` within this option. + +Normally, specify `--video_sections 1` to indicate only one section (one image). + +Increasing `target_index` from the default of 9 may result in larger changes. It has been confirmed that generation can be performed without breaking up to around 40. + +The `--one_frame_auto_resize` option has been added to automatically adjust the image size based on the control image size when `--one_frame_inference` is specified. If this option is enabled, the image size will be adjusted to the nearest bucket size with the specified width\*height, based on the control image size while maintaining the aspect ratio. This can be useful when the multiple generation of images with different sizes is required. + +The `--end_image_path` is ignored for one frame inference. + +
+日本語 + +**この機能は非常に実験的であり**、公式にはサポートされていません。FramePackを使用して1フレーム推論の可能性を試したいユーザーに向けたものです。 + +このスクリプトでは、単一画像の推論を行うこともできます。FramePack公式の機能ではなく、独自の実装です。 + +理論的には、開始画像から、プロンプトに従い、指定時間経過後の画像を生成します。つまり制限付きですが自然言語による画像編集を行うことができます。 + +単一画像推論を行うには`--one_frame_inference`オプションに、何らかのオプションを指定してください。記述例は以下の通りです。 + +```bash +--video_sections 1 --output_type latent_images --one_frame_inference default --image_path start_image.png --control_image_path start_image.png +``` + +`--image_path`は、1フレーム推論ではSIGCLIPの特徴量を取得するために用いられます。通常は開始画像を指定してください。`--control_image_path`は新しく追加された引数で、制御用画像を指定するために用いられますが、通常は開始画像を指定してください。 + +`--one_frame_inference`のオプションは、`default`または `no_2x,no_4x`を推奨します。`--output_type`に`latent_images`を指定するとlatentと画像の両方が保存されます。 + +`--one_frame_inference`のオプションには、カンマ区切りで以下のオプションを任意個数指定できます。 + +- `no_2x`: ゼロベクトルの clean latents 2xをモデルに渡さずに生成します。わずかに生成速度が向上します。生成結果への影響は不明です。 +- `no_4x`: ゼロベクトルの clean latents 4xをモデルに渡さずに生成します。わずかに生成速度が向上します。生成結果への影響は不明です。 +- `no_post`: ゼロベクトルの clean latents の post を渡さずに生成します。生成速度が20%程度向上しますが、生成結果が不安定になる場合があります。 +- `target_index=<整数>`: 生成する画像のindexを指定します。デフォルトは最後のフレームです(=latent_window_size)。 + +たとえば、`--one_frame_inference default`を使用すると、clean latents 2x、clean latents 4x、postをモデルに渡します。`--one_frame_inference no_2x,no_4x`を使用すると、clean latents 2xと4xをモデルに渡すのをスキップします。`--one_frame_inference target_index=9`を使用して、生成する画像のターゲットインデックスを指定できます。 + +後述の高度な推論では、このオプション内で `target_index`、`control_index` といった追加のパラメータを指定して、より詳細な制御が可能です。 + +clean latents 2x、clean latents 4x、postをモデルに渡す場合でも値はゼロベクトルですが、値を渡すか否かで結果は変わります。特に`no_post`を指定すると、`latent_window_size`を大きくしたときに生成結果が不安定になる場合があります。 + +通常は`--video_sections 1` として1セクションのみ(画像1枚)を指定してください。 + +`target_index` をデフォルトの9から大きくすると、変化量が大きくなる可能性があります。40程度までは破綻なく生成されることを確認しています。 + +`--one_frame_auto_resize`オプションが追加されました。`--one_frame_inference`を指定した場合に、制御用画像のサイズに基づいて自動的に画像サイズを調整します。このオプションを有効にすると、画像サイズは、アスペクト比を維持しつつ制御用画像のサイズを基準に、指定された幅\*高さの最も近いバケットサイズに調整されます。異なるサイズの画像を複数生成する必要がある場合に便利です。 + +`--end_image_path`は無視されます。 + +
+ +## kisekaeichi method (Post Reference Options) and 1f-mc (Multi-Control) / kisekaeichi方式(ポスト参照オプション)と1f-mc(マルチコントロール) + +The `kisekaeichi` method was proposed by furusu. The `1f-mc` method was proposed by mattyamonaca in pull request [#304](https://github.com/kohya-ss/musubi-tuner/pull/304). + +In this repository, these methods have been integrated and can be specified with the `--one_frame_inference` option. This allows for specifying any number of control images as clean latents, along with indices. This means you can specify multiple starting images and multiple clean latent posts. Additionally, masks can be applied to each image. + +It is expected to work only with FramePack (non-F1 model) and not with F1 models. + +The following options have been added to `--one_frame_inference`. These can be used in conjunction with existing flags like `target_index`, `no_post`, `no_2x`, and `no_4x`. + +- `control_index=`: Specifies the index(es) of the clean latent for the control image(s). You must specify the same number of indices as the number of control images specified with `--control_image_path`. + +Additionally, the following command-line options have been added. These arguments are only valid when `--one_frame_inference` is specified. + +- `--control_image_path [ ...]` : Specifies the path(s) to control (reference) image(s) for one frame inference. Provide one or more paths separated by spaces. Images with an alpha channel can be specified. If an alpha channel is present, it is used as a mask for the clean latent. +- `--control_image_mask_path [ ...]` : Specifies the path(s) to grayscale mask(s) to be applied to the control image(s). Provide one or more paths separated by spaces. Each mask is applied to the corresponding control image. The 255 areas are referenced, while the 0 areas are ignored. + +**Example of specifying kisekaeichi:** + +The kisekaeichi method works without training, but using a dedicated LoRA may yield better results. + +```bash +--video_sections 1 --output_type latent_images --image_path start_image.png --control_image_path start_image.png clean_latent_post_image.png \ +--one_frame_inference target_index=1,control_index=0;10,no_post,no_2x,no_4x --control_image_mask_path ctrl_mask1.png ctrl_mask2.png +``` + +In this example, `start_image.png` (for `clean_latent_pre`) and `clean_latent_post_image.png` (for `clean_latent_post`) are the reference images. The `target_index` specifies the index of the generated image. The `control_index` specifies the clean latent index for each control image, so it will be `0;10`. The masks for the control images are specified with `--control_image_mask_path`. + +The optimal values for `target_index` and `control_index` are unknown. The `target_index` should be specified as 1 or higher. The `control_index` should be set to an appropriate value relative to `latent_window_size`. Specifying 1 for `target_index` results in less change from the starting image, but may introduce noise. Specifying 9 or 13 may reduce noise but result in larger changes from the original image. + +The `control_index` should be larger than `target_index`. Typically, it is set to `10`, but larger values (e.g., around `13-16`) may also work. + +Sample images and command lines for reproduction are as follows: + +```bash +python fpack_generate_video.py --video_size 832 480 --video_sections 1 --infer_steps 25 \ + --prompt "The girl in a school blazer in a classroom." --save_path path/to/output --output_type latent_images \ + --dit path/to/dit --vae path/to/vae --text_encoder1 path/to/text_encoder1 --text_encoder2 path/to/text_encoder2 \ + --image_encoder path/to/image_encoder --attn_mode sdpa --vae_spatial_tile_sample_min_size 128 --vae_chunk_size 32 \ + --image_path path/to/kisekaeichi_start.png --control_image_path path/to/kisekaeichi_start.png path/to/kisekaeichi_ref.png + --one_frame_inference target_index=1,control_index=0;10,no_2x,no_4x,no_post + --control_image_mask_path path/to/kisekaeichi_start_mask.png path/to/kisekaeichi_ref_mask.png --seed 1234 +``` + +Specify `--fp8_scaled` and `--blocks_to_swap` options according to your VRAM capacity. + +- [kisekaeichi_start.png](./kisekaeichi_start.png) +- [kisekaeichi_ref.png](./kisekaeichi_ref.png) +- [kisekaeichi_start_mask.png](./kisekaeichi_start_mask.png) +- [kisekaeichi_ref_mask.png](./kisekaeichi_ref_mask.png) + +Generation result: [kisekaeichi_result.png](./kisekaeichi_result.png) + + +**Example of 1f-mc (Multi-Control):** + +```bash +--video_sections 1 --output_type latent_images --image_path start_image.png --control_image_path start_image.png 2nd_image.png \ +--one_frame_inference target_index=9,control_index=0;1,no_2x,no_4x +``` + +In this example, `start_image.png` is the starting image, and `2nd_image.png` is the reference image. The `target_index=9` specifies the index of the generated image, while `control_index=0;1` specifies the clean latent indices for each control image. + +1f-mc is intended to be used in combination with a trained LoRA, so adjust `target_index` and `control_index` according to the LoRA's description. + +
+日本語 + +`kisekaeichi`方式はfurusu氏により提案されました。また`1f-mc`方式はmattyamonaca氏によりPR [#304](https://github.com/kohya-ss/musubi-tuner/pull/304) で提案されました。 + +当リポジトリではこれらの方式を統合し、`--one_frame_inference`オプションで指定できるようにしました。これにより、任意の枚数の制御用画像を clean latentとして指定し、さらにインデックスを指定できます。つまり開始画像の複数枚指定やclean latent postの複数枚指定などが可能です。また、それぞれの画像にマスクを適用することもできます。 + +なお、FramePack無印のみ動作し、F1モデルでは動作しないと思われます。 + +`--one_frame_inference`に以下のオプションが追加されています。`target_index`、`no_post`、`no_2x`や`no_4x`など既存のフラグと併用できます。 + +- `control_index=<整数またはセミコロン区切りの整数>`: 制御用画像のclean latentのインデックスを指定します。`--control_image_path`で指定した制御用画像の数と同じ数のインデックスを指定してください。 + +またコマンドラインオプションに以下が追加されています。これらの引数は`--one_frame_inference`を指定した場合のみ有効です。 + +- `--control_image_path <パス1> [<パス2> ...]` : 1フレーム推論用の制御用(参照)画像のパスを1つ以上、スペース区切りで指定します。アルファチャンネルを持つ画像が指定可能です。アルファチャンネルがある場合は、clean latentへのマスクとして利用されます。 +- `--control_image_mask_path <パス1> [<パス2> ...]` : 制御用画像に適用するグレースケールマスクのパスを1つ以上、スペース区切りで指定します。各マスクは対応する制御用画像に適用されます。255の部分が参照される部分、0の部分が無視される部分です。 + +**kisekaeichiの指定例**: + +kisekaeichi方式は学習なしでも動作しますが、専用のLoRAを使用することで、より良い結果が得られる可能性があります。 + +```bash +--video_sections 1 --output_type latent_images --image_path start_image.png --control_image_path start_image.png clean_latent_post_image.png \ +--one_frame_inference target_index=1,control_index=0;10,no_post,no_2x,no_4x --control_image_mask_path ctrl_mask1.png ctrl_mask2.png +``` + +`start_image.png`(clean_latent_preに相当)と`clean_latent_post_image.png`は参照画像(clean_latent_postに相当)です。`target_index`は生成する画像のインデックスを指定します。`control_index`はそれぞれの制御用画像のclean latent indexを指定しますので、`0;10` になります。また`--control_image_mask_path`に制御用画像に適用するマスクを指定します。 + +`target_index`、`control_index`の最適値は不明です。`target_index`は1以上を指定してください。`control_index`は`latent_window_size`に対して適切な値を指定してください。`target_index`に1を指定すると開始画像からの変化が少なくなりますが、ノイズが乗ったりすることが多いようです。9や13などを指定するとノイズは改善されるかもしれませんが、元の画像からの変化が大きくなります。 + +`control_index`は`target_index`より大きい値を指定してください。通常は`10`ですが、これ以上大きな値、たとえば`13~16程度でも動作するようです。 + +サンプル画像と再現のためのコマンドラインは以下のようになります。 + +```bash +python fpack_generate_video.py --video_size 832 480 --video_sections 1 --infer_steps 25 \ + --prompt "The girl in a school blazer in a classroom." --save_path path/to/output --output_type latent_images \ + --dit path/to/dit --vae path/to/vae --text_encoder1 path/to/text_encoder1 --text_encoder2 path/to/text_encoder2 \ + --image_encoder path/to/image_encoder --attn_mode sdpa --vae_spatial_tile_sample_min_size 128 --vae_chunk_size 32 \ + --image_path path/to/kisekaeichi_start.png --control_image_path path/to/kisekaeichi_start.png path/to/kisekaeichi_ref.png + --one_frame_inference target_index=1,control_index=0;10,no_2x,no_4x,no_post + --control_image_mask_path path/to/kisekaeichi_start_mask.png path/to/kisekaeichi_ref_mask.png --seed 1234 +``` + +VRAM容量に応じて、`--fp8_scaled`や`--blocks_to_swap`等のオプションを調整してください。 + +- [kisekaeichi_start.png](./kisekaeichi_start.png) +- [kisekaeichi_ref.png](./kisekaeichi_ref.png) +- [kisekaeichi_start_mask.png](./kisekaeichi_start_mask.png) +- [kisekaeichi_ref_mask.png](./kisekaeichi_ref_mask.png) + +生成結果: +- [kisekaeichi_result.png](./kisekaeichi_result.png) + +**1f-mcの指定例**: + +```bash +--video_sections 1 --output_type latent_images --image_path start_image.png --control_image_path start_image.png 2nd_image.png \ +--one_frame_inference target_index=9,control_index=0;1,no_2x,no_4x +``` + +この例では、`start_image.png`が開始画像で、`2nd_image.png`が参照画像です。`target_index=9`は生成する画像のインデックスを指定し、`control_index=0;1`はそれぞれの制御用画像のclean latent indexを指定しています。 + +1f-mcは学習したLoRAと組み合わせることを想定していますので、そのLoRAの説明に従って、`target_index`や`control_index`を調整してください。 + +
\ No newline at end of file diff --git a/VRGDG_Musubi-tuner/docs/hunyuan_video.md b/VRGDG_Musubi-tuner/docs/hunyuan_video.md new file mode 100644 index 0000000000000000000000000000000000000000..7a14f3658314159e48b705a26b662be50a84ad61 --- /dev/null +++ b/VRGDG_Musubi-tuner/docs/hunyuan_video.md @@ -0,0 +1,553 @@ +> 📝 Click on the language section to expand / 言語をクリックして展開 + +# HunyuanVideo + +## Overview / 概要 + +This document describes the usage of the [HunyuanVideo](https://github.com/Tencent/HunyuanVideo) architecture within the Musubi Tuner framework. HunyuanVideo is a video generation model that supports text-to-video generation. + +This feature is experimental. + +
+日本語 + +このドキュメントは、Musubi Tunerフレームワーク内での[HunyuanVideo](https://github.com/Tencent/HunyuanVideo)アーキテクチャの使用法について説明しています。HunyuanVideoはテキストから動画を生成するモデルです。 + +この機能は実験的なものです。 +
+ +## Download the model / モデルのダウンロード + +There are two ways to download the model. + +### Use the Official HunyuanVideo Model / 公式HunyuanVideoモデルを使う + +Download the model following the [official README](https://github.com/Tencent/HunyuanVideo/blob/main/ckpts/README.md) and place it in your chosen directory with the following structure: + +``` + ckpts + ├──hunyuan-video-t2v-720p + │ ├──transformers + │ ├──vae + ├──text_encoder + ├──text_encoder_2 + ├──... +``` + +### Using ComfyUI Models for Text Encoder / Text EncoderにComfyUI提供のモデルを使う + +This method is easier. + +For DiT and VAE, use the HunyuanVideo models. + +From https://huggingface.co/tencent/HunyuanVideo/tree/main/hunyuan-video-t2v-720p/transformers, download [mp_rank_00_model_states.pt](https://huggingface.co/tencent/HunyuanVideo/resolve/main/hunyuan-video-t2v-720p/transformers/mp_rank_00_model_states.pt) and place it in your chosen directory. + +(Note: The fp8 model on the same page is unverified.) + +If you are training with `--fp8_base`, you can use `mp_rank_00_model_states_fp8.safetensors` from [here](https://huggingface.co/kohya-ss/HunyuanVideo-fp8_e4m3fn-unofficial) instead of `mp_rank_00_model_states.pt`. (This file is unofficial and simply converts the weights to float8_e4m3fn.) + +From https://huggingface.co/tencent/HunyuanVideo/tree/main/hunyuan-video-t2v-720p/vae, download [pytorch_model.pt](https://huggingface.co/tencent/HunyuanVideo/resolve/main/hunyuan-video-t2v-720p/vae/pytorch_model.pt) and place it in your chosen directory. + +For the Text Encoder, use the models provided by ComfyUI. Refer to [ComfyUI's page](https://comfyanonymous.github.io/ComfyUI_examples/hunyuan_video/), from https://huggingface.co/Comfy-Org/HunyuanVideo_repackaged/tree/main/split_files/text_encoders, download `llava_llama3_fp16.safetensors` (Text Encoder 1, LLM) and `clip_l.safetensors` (Text Encoder 2, CLIP) and place them in your chosen directory. + +(Note: The fp8 LLM model on the same page is unverified.) + +
+日本語 + +以下のいずれかの方法で、モデルをダウンロードしてください。 + +### HunyuanVideoの公式モデルを使う + +[公式のREADME](https://github.com/Tencent/HunyuanVideo/blob/main/ckpts/README.md)を参考にダウンロードし、任意のディレクトリに以下のように配置します。 + +``` + ckpts + ├──hunyuan-video-t2v-720p + │ ├──transformers + │ ├──vae + ├──text_encoder + ├──text_encoder_2 + ├──... +``` + +### Text EncoderにComfyUI提供のモデルを使う + +こちらの方法の方がより簡単です。DiTとVAEのモデルはHumyuanVideoのものを使用します。 + +https://huggingface.co/tencent/HunyuanVideo/tree/main/hunyuan-video-t2v-720p/transformers から、[mp_rank_00_model_states.pt](https://huggingface.co/tencent/HunyuanVideo/resolve/main/hunyuan-video-t2v-720p/transformers/mp_rank_00_model_states.pt) をダウンロードし、任意のディレクトリに配置します。 + +(同じページにfp8のモデルもありますが、未検証です。) + +`--fp8_base`を指定して学習する場合は、`mp_rank_00_model_states.pt`の代わりに、[こちら](https://huggingface.co/kohya-ss/HunyuanVideo-fp8_e4m3fn-unofficial)の`mp_rank_00_model_states_fp8.safetensors`を使用可能です。(このファイルは非公式のもので、重みを単純にfloat8_e4m3fnに変換したものです。) + +また、https://huggingface.co/tencent/HunyuanVideo/tree/main/hunyuan-video-t2v-720p/vae から、[pytorch_model.pt](https://huggingface.co/tencent/HunyuanVideo/resolve/main/hunyuan-video-t2v-720p/vae/pytorch_model.pt) をダウンロードし、任意のディレクトリに配置します。 + +Text EncoderにはComfyUI提供のモデルを使用させていただきます。[ComyUIのページ](https://comfyanonymous.github.io/ComfyUI_examples/hunyuan_video/)を参考に、https://huggingface.co/Comfy-Org/HunyuanVideo_repackaged/tree/main/split_files/text_encoders から、llava_llama3_fp16.safetensors (Text Encoder 1、LLM)と、clip_l.safetensors (Text Encoder 2、CLIP)をダウンロードし、任意のディレクトリに配置します。 + +(同じページにfp8のLLMモデルもありますが、動作未検証です。) + +
+ +## Pre-caching / 事前キャッシング + +### Latent Pre-caching / latentの事前キャッシング + +Latent pre-caching is required. Create the cache using the following command: + +If you have installed using pip: + +```bash +python src/musubi_tuner/cache_latents.py --dataset_config path/to/toml --vae path/to/ckpts/hunyuan-video-t2v-720p/vae/pytorch_model.pt --vae_chunk_size 32 --vae_tiling +``` + +If you have installed with `uv`, you can use `uv run --extra cu124` to run the script. If CUDA 12.8 or 13.0 is supported, `uv run --extra cu128` or `uv run --extra cu130` is also available. Other scripts can be run in the same way. (Note that the installation with `uv` is experimental. Feedback is welcome. If you encounter any issues, please use the pip-based installation.) + +```bash +uv run --extra cu124 src/musubi_tuner/cache_latents.py --dataset_config path/to/toml --vae path/to/ckpts/hunyuan-video-t2v-720p/vae/pytorch_model.pt --vae_chunk_size 32 --vae_tiling +``` + +For additional options, use `python src/musubi_tuner/cache_latents.py --help`. + +If you're running low on VRAM, reduce `--vae_spatial_tile_sample_min_size` to around 128 and lower the `--batch_size` (`--vae_spatial_tile_sample_min_size` may not exist in architectures other than HunyuanVideo, see the documentation for each architecture). + +If you are using an AMD GPU and/or are experiencing slow latent caching, consider trying `--disable_cudnn_backend`. For some details, see [this pull request](https://github.com/kohya-ss/musubi-tuner/pull/592). + +Use `--debug_mode image` to display dataset images and captions in a new window, or `--debug_mode console` to display them in the console (requires `ascii-magic`). + +With `--debug_mode video`, images or videos will be saved in the cache directory (please delete them after checking). The bitrate of the saved video is set to 1Mbps for preview purposes. The images decoded from the original video (not degraded) are used for the cache (for training). + +When `--debug_mode` is specified, the actual caching process is not performed. + +By default, cache files not included in the dataset are automatically deleted. You can still keep cache files as before by specifying `--keep_cache`. + +
+日本語 + +latentの事前キャッシュは必須です。以下のコマンドを使用して、事前キャッシュを作成してください。(pipによるインストールの場合) + +```bash +python src/musubi_tuner/cache_latents.py --dataset_config path/to/toml --vae path/to/ckpts/hunyuan-video-t2v-720p/vae/pytorch_model.pt --vae_chunk_size 32 --vae_tiling +``` + +uvでインストールした場合は、`uv run --extra cu124 python src/musubi_tuner/cache_latents.py ...`のように、`uv run --extra cu124`を先頭につけてください。CUDA 12.8や13.0に対応している場合は、`uv run --extra cu128`や`uv run --extra cu130`も利用可能です。以下のコマンドも同様です。 + +その他のオプションは`python src/musubi_tuner/cache_latents.py --help`で確認できます。 + +VRAMが足りない場合は、`--vae_spatial_tile_sample_min_size`を128程度に減らし、`--batch_size`を小さくしてください。 + +`--debug_mode image` を指定するとデータセットの画像とキャプションが新規ウィンドウに表示されます。`--debug_mode console`でコンソールに表示されます(`ascii-magic`が必要)。 + +`--debug_mode video`で、キャッシュディレクトリに画像または動画が保存されます(確認後、削除してください)。動画のビットレートは確認用に低くしてあります。実際には元動画の画像が学習に使用されます。 + +`--debug_mode`指定時は、実際のキャッシュ処理は行われません。 + +デフォルトではデータセットに含まれないキャッシュファイルは自動的に削除されます。`--keep_cache`を指定すると、キャッシュファイルを残すことができます。 + +
+ +### Text Encoder Output Pre-caching / テキストエンコーダー出力の事前キャッシング + +Text Encoder output pre-caching is required. Create the cache using the following command: + +```bash +python src/musubi_tuner/cache_text_encoder_outputs.py --dataset_config path/to/toml --text_encoder1 path/to/ckpts/text_encoder --text_encoder2 path/to/ckpts/text_encoder_2 --batch_size 16 +``` + +or for uv: + +```bash +uv run --extra cu124 src/musubi_tuner/cache_text_encoder_outputs.py --dataset_config path/to/toml --text_encoder1 path/to/ckpts/text_encoder --text_encoder2 path/to/ckpts/text_encoder_2 --batch_size 16 +``` + +For additional options, use `python src/musubi_tuner/cache_text_encoder_outputs.py --help`. + +Adjust `--batch_size` according to your available VRAM. + +For systems with limited VRAM (less than ~16GB), use `--fp8_llm` to run the LLM in fp8 mode. + +By default, cache files not included in the dataset are automatically deleted. You can still keep cache files as before by specifying `--keep_cache`. + +
+日本語 + +Text Encoder出力の事前キャッシュは必須です。以下のコマンドを使用して、事前キャッシュを作成してください。 + +```bash +python src/musubi_tuner/cache_text_encoder_outputs.py --dataset_config path/to/toml --text_encoder1 path/to/ckpts/text_encoder --text_encoder2 path/to/ckpts/text_encoder_2 --batch_size 16 +``` + +その他のオプションは`python src/musubi_tuner/cache_text_encoder_outputs.py --help`で確認できます。 + +`--batch_size`はVRAMに合わせて調整してください。 + +VRAMが足りない場合(16GB程度未満の場合)は、`--fp8_llm`を指定して、fp8でLLMを実行してください。 + +デフォルトではデータセットに含まれないキャッシュファイルは自動的に削除されます。`--keep_cache`を指定すると、キャッシュファイルを残すことができます。 + +
+ +## Training / 学習 + +Start training using the following command (input as a single line): + +```bash +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 src/musubi_tuner/hv_train_network.py + --dit path/to/ckpts/hunyuan-video-t2v-720p/transformers/mp_rank_00_model_states.pt + --dataset_config path/to/toml --sdpa --mixed_precision bf16 --fp8_base + --optimizer_type adamw8bit --learning_rate 2e-4 --gradient_checkpointing + --max_data_loader_n_workers 2 --persistent_data_loader_workers + --network_module networks.lora --network_dim 32 + --timestep_sampling shift --discrete_flow_shift 7.0 + --max_train_epochs 16 --save_every_n_epochs 1 --seed 42 + --output_dir path/to/output_dir --output_name name-of-lora +``` + +or for uv: + +```bash +uv run --extra cu124 accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 src/musubi_tuner/hv_train_network.py + --dit path/to/ckpts/hunyuan-video-t2v-720p/transformers/mp_rank_00_model_states.pt + --dataset_config path/to/toml --sdpa --mixed_precision bf16 --fp8_base + --optimizer_type adamw8bit --learning_rate 2e-4 --gradient_checkpointing + --max_data_loader_n_workers 2 --persistent_data_loader_workers + --network_module networks.lora --network_dim 32 + --timestep_sampling shift --discrete_flow_shift 7.0 + --max_train_epochs 16 --save_every_n_epochs 1 --seed 42 + --output_dir path/to/output_dir --output_name name-of-lora +``` + +If the details of the image are not learned well, try lowering the discrete flow shift to around 3.0. + +The training settings are still experimental. Appropriate learning rates, training steps, timestep distribution, loss weighting, etc. are not yet known. Feedback is welcome. + +For additional options, use `python src/musubi_tuner/hv_train_network.py --help` (note that many options are unverified). + +### Memory Optimization + +`--gradient_checkpointing` enables gradient checkpointing to reduce VRAM usage. Gradient checkpointing is a memory-saving technique that trades off computation time for memory usage by recomputing certain intermediate results during the backward pass instead of storing them all in memory. This is particularly useful for training large models such as HunyuanVideo, where VRAM can be a limiting factor. However, it may slow down training. If you have sufficient VRAM, you can disable it. + +Specifying `--fp8_base` runs DiT in fp8 mode. Without this flag, mixed precision data type will be used. fp8 can significantly reduce memory consumption but may impact output quality. If `--fp8_base` is not specified, 24GB or more VRAM is recommended. Use `--blocks_to_swap` as needed. + +If you're running low on VRAM, use `--blocks_to_swap` to offload some blocks to CPU. Maximum value is 36. + +(The idea of block swap is based on the implementation by 2kpr. Thanks again to 2kpr.) + +`--use_pinned_memory_for_block_swap` can be used to enable pinned memory for block swapping. This may improve performance when swapping blocks between CPU and GPU. However, it may increase shared VRAM usage on Windows systems. Use this option based on your system configuration (e.g., available system RAM and VRAM). In some environments, not specifying this option may result in faster performance. + +`--gradient_checkpointing_cpu_offload` can be used to offload activations to CPU when using gradient checkpointing. This can further reduce VRAM usage, but may slow down training. This option is especially useful when the latent resolution (or video length) is high and VRAM is limited. This option must be used together with `--gradient_checkpointing`. See [PR #537](https://github.com/kohya-ss/musubi-tuner/pull/537) for more details. + +### Attention + +Use `--sdpa` for PyTorch's scaled dot product attention. Use `--flash_attn` for [FlashAttention](https://github.com/Dao-AILab/flash-attention). Use `--xformers` for xformers, but specify `--split_attn` when using xformers. `--sage_attn` for SageAttention, but SageAttention is not yet supported for training, so it raises a ValueError. + +`--split_attn` processes attention in chunks. Speed may be slightly reduced, but VRAM usage is slightly reduced. + +### Timestep Sampling +You can also specify the range of timesteps +with `--min_timestep` and `--max_timestep`. See [advanced configuration](../advanced_config.md#specify-time-step-range-for-training--学習時のタイムステップ範囲の指定) for details. + +`--show_timesteps` can be set to `image` (requires `matplotlib`) or `console` to display timestep distribution and loss weighting during training. (When using `flux_shift` and `qwen_shift`, the distribution will be for images with a resolution of 1024x1024.) + +### Other Options + +The format of LoRA trained is the same as `sd-scripts`. + +You can record logs during training. Refer to [Save and view logs in TensorBoard format](../advanced_config.md#save-and-view-logs-in-tensorboard-format--tensorboard形式のログの保存と参照). + +For PyTorch Dynamo optimization, refer to [this document](../advanced_config.md#pytorch-dynamo-optimization-for-model-training--モデルの学習におけるpytorch-dynamoの最適化). + +For sample image generation during training, refer to [this document](../sampling_during_training.md). For advanced configuration, refer to [this document](../advanced_config.md). + +
+日本語 + +以下のコマンドを使用して、学習を開始します(実際には一行で入力してください)。 + +```bash +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 src/musubi_tuner/hv_train_network.py + --dit path/to/ckpts/hunyuan-video-t2v-720p/transformers/mp_rank_00_model_states.pt + --dataset_config path/to/toml --sdpa --mixed_precision bf16 --fp8_base + --optimizer_type adamw8bit --learning_rate 2e-4 --gradient_checkpointing + --max_data_loader_n_workers 2 --persistent_data_loader_workers + --network_module networks.lora --network_dim 32 + --timestep_sampling shift --discrete_flow_shift 7.0 + --max_train_epochs 16 --save_every_n_epochs 1 --seed 42 + --output_dir path/to/output_dir --output_name name-of-lora +``` + +ディテールが甘くなる場合は、discrete flow shiftを3.0程度に下げてみてください。 + +ただ、適切な学習率、学習ステップ数、timestepsの分布、loss weightingなどのパラメータは、以前として不明な点が数多くあります。情報提供をお待ちしています。 + +その他のオプションは`python src/musubi_tuner/hv_train_network.py --help`で確認できます(ただし多くのオプションは動作未確認です)。 + +**メモリ最適化** + +`--gradient_checkpointing`でgradient checkpointingを有効にします。VRAM使用量を削減できます。gradient checkpointingは、バックワードパス中に一部の中間結果をすべてメモリに保存するのではなく、再計算することで、計算時間とメモリ使用量をトレードオフするメモリ節約技術です。HunyuanVideoのような大規模モデルの学習ではVRAMが制約となることが多いため、特に有用です。ただし学習が遅くなる可能性があります。十分なVRAMがある場合は無効にしても構いません。 + +`--fp8_base`を指定すると、DiTがfp8で学習されます。未指定時はmixed precisionのデータ型が使用されます。fp8は大きく消費メモリを削減できますが、品質は低下する可能性があります。`--fp8_base`を指定しない場合はVRAM 24GB以上を推奨します。また必要に応じて`--blocks_to_swap`を使用してください。 + +VRAMが足りない場合は、`--blocks_to_swap`を指定して、一部のブロックをCPUにオフロードしてください。最大36が指定できます。 + +(block swapのアイデアは2kpr氏の実装に基づくものです。2kpr氏にあらためて感謝します。) + +`--use_pinned_memory_for_block_swap`を指定すると、block swapにピン留めメモリを使用します。CPUとGPU間でブロックをスワップする際のパフォーマンスが向上する可能性があります。ただし、Windows環境では共有VRAM使用量が増加する可能性があります。システム構成(利用可能なシステムRAMやVRAMなど)に応じて、このオプションを使用してください。環境によっては指定しないほうが高速になる場合もあります。 + +`--gradient_checkpointing_cpu_offload`を指定すると、gradient checkpointing使用時にアクティベーションをCPUにオフロードします。これによりVRAM使用量をさらに削減できますが、学習が遅くなる可能性があります。latent解像度(または動画長)が高く、VRAMが限られている場合に特に有用です。このオプションは`--gradient_checkpointing`と併用する必要があります。詳細は[PR #537](https://github.com/Dao-AILab/flash-attention/pull/537)を参照してください。 + +**Attention** + +`--sdpa`でPyTorchのscaled dot product attentionを使用します。`--flash_attn`で[FlashAttention]:(https://github.com/Dao-AILab/flash-attention)を使用します。`--xformers`でxformersの利用も可能ですが、xformersを使う場合は`--split_attn`を指定してください。`--sage_attn`でSageAttentionを使用しますが、SageAttentionは現時点では学習に未対応のため、エラーが発生します。 + +`--split_attn`を指定すると、attentionを分割して処理します。速度が多少低下しますが、VRAM使用量はわずかに減ります。 + +**タイムステップサンプリング** + +`--min_timestep`と`--max_timestep`を指定すると、学習時のタイムステップの範囲を指定できます。詳細は[高度な設定](../advanced_config.md#specify-time-step-range-for-training--学習時のタイムステップ範囲の指定)を参照してください。 + +`--show_timesteps`に`image`(`matplotlib`が必要)または`console`を指定すると、学習時のtimestepsの分布とtimestepsごとのloss weightingが確認できます。(`flux_shift`と`qwen_shift`を使用する場合は画像の解像度が1024x1024の場合の分布になります。) + +**その他のオプション** + +学習されるLoRAの形式は、`sd-scripts`と同じです。 + +学習時のログの記録が可能です。[TensorBoard形式のログの保存と参照](../advanced_config.md#save-and-view-logs-in-tensorboard-format--tensorboard形式のログの保存と参照)を参照してください。 + +PyTorch Dynamoによる最適化を行う場合は、[こちら](../advanced_config.md#pytorch-dynamo-optimization-for-model-training--モデルの学習におけるpytorch-dynamoの最適化)を参照してください。 + +学習中のサンプル画像生成については、[こちらのドキュメント](../sampling_during_training.md)を参照してください。その他の高度な設定については[こちらのドキュメント](../advanced_config.md)を参照してください。 + +
+ +### Merging LoRA Weights / LoRAの重みのマージ + +```bash +python src/musubi_tuner/merge_lora.py \ + --dit path/to/ckpts/hunyuan-video-t2v-720p/transformers/mp_rank_00_model_states.pt \ + --lora_weight path/to/lora.safetensors \ + --save_merged_model path/to/merged_model.safetensors \ + --device cpu \ + --lora_multiplier 1.0 +``` + +or for uv: + +```bash +uv run --extra cu124 src/musubi_tuner/merge_lora.py \ + --dit path/to/ckpts/hunyuan-video-t2v-720p/transformers/mp_rank_00_model_states.pt \ + --lora_weight path/to/lora.safetensors \ + --save_merged_model path/to/merged_model.safetensors \ + --device cpu \ + --lora_multiplier 1.0 +``` + +Specify the device to perform the calculation (`cpu` or `cuda`, etc.) with `--device`. Calculation will be faster if `cuda` is specified. + +Specify the LoRA weights to merge with `--lora_weight` and the multiplier for the LoRA weights with `--lora_multiplier`. Multiple values can be specified, and the number of values must match. + +
+日本語 + +```bash +python src/musubi_tuner/merge_lora.py \ + --dit path/to/ckpts/hunyuan-video-t2v-720p/transformers/mp_rank_00_model_states.pt \ + --lora_weight path/to/lora.safetensors \ + --save_merged_model path/to/merged_model.safetensors \ + --device cpu \ + --lora_multiplier 1.0 +``` + +`--device`には計算を行うデバイス(`cpu`または`cuda`等)を指定してください。`cuda`を指定すると計算が高速化されます。 + +`--lora_weight`にはマージするLoRAの重みを、`--lora_multiplier`にはLoRAの重みの係数を、それぞれ指定してください。複数個が指定可能で、両者の数は一致させてください。 + +
+ +## Inference / 推論 + +Generate videos using the following command: + +```bash +python src/musubi_tuner/hv_generate_video.py --fp8 --video_size 544 960 --video_length 5 --infer_steps 30 + --prompt "A cat walks on the grass, realistic style." --save_path path/to/save/dir --output_type both + --dit path/to/ckpts/hunyuan-video-t2v-720p/transformers/mp_rank_00_model_states.pt --attn_mode sdpa --split_attn + --vae path/to/ckpts/hunyuan-video-t2v-720p/vae/pytorch_model.pt + --vae_chunk_size 32 --vae_spatial_tile_sample_min_size 128 + --text_encoder1 path/to/ckpts/text_encoder + --text_encoder2 path/to/ckpts/text_encoder_2 + --seed 1234 --lora_multiplier 1.0 --lora_weight path/to/lora.safetensors +``` + +or for uv: + +```bash +uv run --extra cu124 src/musubi_tuner/hv_generate_video.py --fp8 --video_size 544 960 --video_length 5 --infer_steps 30 + --prompt "A cat walks on the grass, realistic style." --save_path path/to/save/dir --output_type both + --dit path/to/ckpts/hunyuan-video-t2v-720p/transformers/mp_rank_00_model_states.pt --attn_mode sdpa --split_attn + --vae path/to/ckpts/hunyuan-video-t2v-720p/vae/pytorch_model.pt + --vae_chunk_size 32 --vae_spatial_tile_sample_min_size 128 + --text_encoder1 path/to/ckpts/text_encoder + --text_encoder2 path/to/ckpts/text_encoder_2 + --seed 1234 --lora_multiplier 1.0 --lora_weight path/to/lora.safetensors +``` + +For additional options, use `python src/musubi_tuner/hv_generate_video.py --help`. + +Specifying `--fp8` runs DiT in fp8 mode. fp8 can significantly reduce memory consumption but may impact output quality. + +`--fp8_fast` option is also available for faster inference on RTX 40x0 GPUs. This option requires `--fp8` option. + +If you're running low on VRAM, use `--blocks_to_swap` to offload some blocks to CPU. Maximum value is 38. + +For `--attn_mode`, specify either `flash`, `torch`, `sageattn`, `xformers`, or `sdpa` (same as `torch`). These correspond to FlashAttention, scaled dot product attention, SageAttention, and xformers, respectively. Default is `torch`. SageAttention is effective for VRAM reduction. + +Specifing `--split_attn` will process attention in chunks. Inference with SageAttention is expected to be about 10% faster. + +For `--output_type`, specify either `both`, `latent`, `video` or `images`. `both` outputs both latents and video. Recommended to use `both` in case of Out of Memory errors during VAE processing. You can specify saved latents with `--latent_path` and use `--output_type video` (or `images`) to only perform VAE decoding. + +`--seed` is optional. A random seed will be used if not specified. + +`--video_length` should be specified as "a multiple of 4 plus 1". + +`--flow_shift` can be specified to shift the timestep (discrete flow shift). The default value when omitted is 7.0, which is the recommended value for 50 inference steps. In the HunyuanVideo paper, 7.0 is recommended for 50 steps, and 17.0 is recommended for less than 20 steps (e.g. 10). + +By specifying `--video_path`, video2video inference is possible. Specify a video file or a directory containing multiple image files (the image files are sorted by file name and used as frames). An error will occur if the video is shorter than `--video_length`. You can specify the strength with `--strength`. It can be specified from 0 to 1.0, and the larger the value, the greater the change from the original video. + +Note that video2video inference is experimental. + +`--compile` option enables PyTorch's compile feature (experimental). Requires triton. On Windows, also requires Visual C++ build tools installed and PyTorch>=2.6.0 (Visual C++ build tools is also required). See [the torch.compile documentation](torch_compile.md) for details. + +The `--compile` option takes a long time to run the first time, but speeds up on subsequent runs. + +You can save the DiT model after LoRA merge with the `--save_merged_model` option. Specify `--save_merged_model path/to/merged_model.safetensors`. Note that inference will not be performed when this option is specified. + +
+日本語 + +以下のコマンドを使用して動画を生成します。 + +```bash +python src/musubi_tuner/hv_generate_video.py --fp8 --video_size 544 960 --video_length 5 --infer_steps 30 + --prompt "A cat walks on the grass, realistic style." --save_path path/to/save/dir --output_type both + --dit path/to/ckpts/hunyuan-video-t2v-720p/transformers/mp_rank_00_model_states.pt --attn_mode sdpa --split_attn + --vae path/to/ckpts/hunyuan-video-t2v-720p/vae/pytorch_model.pt + --vae_chunk_size 32 --vae_spatial_tile_sample_min_size 128 + --text_encoder1 path/to/ckpts/text_encoder + --text_encoder2 path/to/ckpts/text_encoder_2 + --seed 1234 --lora_multiplier 1.0 --lora_weight path/to/lora.safetensors +``` + +その他のオプションは`python src/musubi_tuner/hv_generate_video.py --help`で確認できます。 + +`--fp8`を指定すると、DiTがfp8で推論されます。fp8は大きく消費メモリを削減できますが、品質は低下する可能性があります。 + +RTX 40x0シリーズのGPUを使用している場合は、`--fp8_fast`オプションを指定することで、高速推論が可能です。このオプションを指定する場合は、`--fp8`も指定してください。 + +VRAMが足りない場合は、`--blocks_to_swap`を指定して、一部のブロックをCPUにオフロードしてください。最大38が指定できます。 + +`--attn_mode`には`flash`、`torch`、`sageattn`、`xformers`または`sdpa`(`torch`指定時と同じ)のいずれかを指定してください。それぞれFlashAttention、scaled dot product attention、SageAttention、xformersに対応します。デフォルトは`torch`です。SageAttentionはVRAMの削減に有効です。 + +`--split_attn`を指定すると、attentionを分割して処理します。SageAttention利用時で10%程度の高速化が見込まれます。 + +`--output_type`には`both`、`latent`、`video`、`images`のいずれかを指定してください。`both`はlatentと動画の両方を出力します。VAEでOut of Memoryエラーが発生する場合に備えて、`both`を指定することをお勧めします。`--latent_path`に保存されたlatentを指定し、`--output_type video` (または`images`)としてスクリプトを実行すると、VAEのdecodeのみを行えます。 + +`--seed`は省略可能です。指定しない場合はランダムなシードが使用されます。 + +`--video_length`は「4の倍数+1」を指定してください。 + +`--flow_shift`にタイムステップのシフト値(discrete flow shift)を指定可能です。省略時のデフォルト値は7.0で、これは推論ステップ数が50の時の推奨値です。HunyuanVideoの論文では、ステップ数50の場合は7.0、ステップ数20未満(10など)で17.0が推奨されています。 + +`--video_path`に読み込む動画を指定すると、video2videoの推論が可能です。動画ファイルを指定するか、複数の画像ファイルが入ったディレクトリを指定してください(画像ファイルはファイル名でソートされ、各フレームとして用いられます)。`--video_length`よりも短い動画を指定するとエラーになります。`--strength`で強度を指定できます。0~1.0で指定でき、大きいほど元の動画からの変化が大きくなります。 + +なおvideo2video推論の処理は実験的なものです。 + +`--compile`オプションでPyTorchのコンパイル機能を有効にします(実験的機能)。tritonのインストールが必要です。また、WindowsではVisual C++ build toolsが必要で、かつPyTorch>=2.6.0でのみ動作します。詳細は[torch.compileのドキュメント](torch_compile.md)を参照してください。 + +`--compile`は初回実行時にかなりの時間がかかりますが、2回目以降は高速化されます。 + +`--save_merged_model`オプションで、LoRAマージ後のDiTモデルを保存できます。`--save_merged_model path/to/merged_model.safetensors`のように指定してください。なおこのオプションを指定すると推論は行われません。 + +
+ +### Inference with SkyReels V1 / SkyReels V1での推論 + +SkyReels V1 T2V and I2V models are supported (inference only). + +The model can be downloaded from [here](https://huggingface.co/Kijai/SkyReels-V1-Hunyuan_comfy). Many thanks to Kijai for providing the model. `skyreels_hunyuan_i2v_bf16.safetensors` is the I2V model, and `skyreels_hunyuan_t2v_bf16.safetensors` is the T2V model. The models other than bf16 are not tested (`fp8_e4m3fn` may work). + +For T2V inference, add the following options to the inference command: + +```bash +--guidance_scale 6.0 --embedded_cfg_scale 1.0 --negative_prompt "Aerial view, aerial view, overexposed, low quality, deformation, a poor composition, bad hands, bad teeth, bad eyes, bad limbs, distortion" --split_uncond +``` + +SkyReels V1 seems to require a classfier free guidance (negative prompt).`--guidance_scale` is a guidance scale for the negative prompt. The recommended value is 6.0 from the official repository. The default is 1.0, it means no classifier free guidance. + +`--embedded_cfg_scale` is a scale of the embedded guidance. The recommended value is 1.0 from the official repository (it may mean no embedded guidance). + +`--negative_prompt` is a negative prompt for the classifier free guidance. The above sample is from the official repository. If you don't specify this, and specify `--guidance_scale` other than 1.0, an empty string will be used as the negative prompt. + +`--split_uncond` is a flag to split the model call into unconditional and conditional parts. This reduces VRAM usage but may slow down inference. If `--split_attn` is specified, `--split_uncond` is automatically set. + +You can also perform image2video inference with SkyReels V1 I2V model. Specify the image file path with `--image_path`. The image will be resized to the given `--video_size`. + +```bash +--image_path path/to/image.jpg +``` + +
+日本語 + +SkyReels V1のT2VとI2Vモデルがサポートされています(推論のみ)。 + +モデルは[こちら](https://huggingface.co/Kijai/SkyReels-V1-Hunyuan_comfy)からダウンロードできます。モデルを提供してくださったKijai氏に感謝します。`skyreels_hunyuan_i2v_bf16.safetensors`がI2Vモデル、`skyreels_hunyuan_t2v_bf16.safetensors`がT2Vモデルです。`bf16`以外の形式は未検証です(`fp8_e4m3fn`は動作するかもしれません)。 + +T2V推論を行う場合、以下のオプションを推論コマンドに追加してください: + +```bash +--guidance_scale 6.0 --embedded_cfg_scale 1.0 --negative_prompt "Aerial view, aerial view, overexposed, low quality, deformation, a poor composition, bad hands, bad teeth, bad eyes, bad limbs, distortion" --split_uncond +``` + +SkyReels V1はclassifier free guidance(ネガティブプロンプト)を必要とするようです。`--guidance_scale`はネガティブプロンプトのガイダンススケールです。公式リポジトリの推奨値は6.0です。デフォルトは1.0で、この場合はclassifier free guidanceは使用されません(ネガティブプロンプトは無視されます)。 + +`--embedded_cfg_scale`は埋め込みガイダンスのスケールです。公式リポジトリの推奨値は1.0です(埋め込みガイダンスなしを意味すると思われます)。 + +`--negative_prompt`はいわゆるネガティブプロンプトです。上記のサンプルは公式リポジトリのものです。`--guidance_scale`を指定し、`--negative_prompt`を指定しなかった場合は、空文字列が使用されます。 + +`--split_uncond`を指定すると、モデル呼び出しをuncondとcond(ネガティブプロンプトとプロンプト)に分割します。VRAM使用量が減りますが、推論速度は低下する可能性があります。`--split_attn`が指定されている場合、`--split_uncond`は自動的に有効になります。 + +
+ +### Convert LoRA to another format / LoRAの形式の変換 + +You can convert LoRA to a format (presumed to be Diffusion-pipe) compatible with another inference environment (Diffusers, ComfyUI etc.) using the following command: + +```bash +python src/musubi_tuner/convert_lora.py --input path/to/musubi_lora.safetensors --output path/to/another_format.safetensors --target other +``` + +or for uv: + +```bash +uv run --extra cu124 src/musubi_tuner/convert_lora.py --input path/to/musubi_lora.safetensors --output path/to/another_format.safetensors --target other +``` + +Specify the input and output file paths with `--input` and `--output`, respectively. + +Specify `other` for `--target`. Use `default` to convert from another format to the format of this repository. + +
+日本語 + +他の推論環境(DiffusersやComfyUI)で使用可能な形式(Diffusion-pipe または Diffusers と思われる)への変換は以下のコマンドで行えます。 + +```bash +python src/musubi_tuner/convert_lora.py --input path/to/musubi_lora.safetensors --output path/to/another_format.safetensors --target other +``` + +`--input`と`--output`はそれぞれ入力と出力のファイルパスを指定してください。 + +`--target`には`other`を指定してください。`default`を指定すると、他の形式から当リポジトリの形式に変換できます。 + +
diff --git a/VRGDG_Musubi-tuner/docs/hunyuan_video_1_5.md b/VRGDG_Musubi-tuner/docs/hunyuan_video_1_5.md new file mode 100644 index 0000000000000000000000000000000000000000..79bc9fe60844e8fda02b03c7d860604c1a91d061 --- /dev/null +++ b/VRGDG_Musubi-tuner/docs/hunyuan_video_1_5.md @@ -0,0 +1,372 @@ +# HunyuanVideo 1.5 + +## Overview / 概要 + +This document describes the usage of HunyuanVideo 1.5 architecture within the Musubi Tuner framework. HunyuanVideo 1.5 is a video generation model that supports both text-to-video (T2V) and image-to-video (I2V) generation. + +Pre-caching, training, and inference options can be found via `--help`. Many options are shared with HunyuanVideo, so refer to the [HunyuanVideo documentation](./hunyuan_video.md) as needed. + +This feature is experimental. + +
+日本語 + +このドキュメントは、Musubi Tunerフレームワーク内でのHunyuanVideo 1.5アーキテクチャの使用法について説明しています。HunyuanVideo 1.5はテキストから動画を生成(T2V)、および画像から動画を生成(I2V)することができるモデルです。 + +事前キャッシング、学習、推論のオプションは`--help`で確認してください。HunyuanVideoと共通のオプションが多くありますので、必要に応じて[HunyuanVideoのドキュメント](./hunyuan_video.md)も参照してください。 + +この機能は実験的なものです。 + +
+ +## Download the model / モデルのダウンロード + +You need to download the DiT, VAE, Text Encoder (Qwen2.5-VL), and BYT5 models. + +- **DiT**: Download from [HuggingFace's HunyuanVideo 1.5 site](https://huggingface.co/tencent/HunyuanVideo-1.5/tree/main). Use `transformer/720p_i2v/diffusion_pytorch_model.safetensors` for I2V DiT and `transformer/720p_t2v/diffusion_pytorch_model.safetensors` for T2V DiT. +Alternatively, you can use `split_files/diffusion_models/hunyuanvideo1.5_720p_i2v_fp16.safetensors` and `split_files/diffusion_models/hunyuanvideo1.5_720p_t2v_fp16.safetensors` from [ComfyUI's HunyuanVideo 1.5 weights](https://huggingface.co/Comfy-Org/HunyuanVideo_1.5_repackaged/tree/main), but do not use these for bf16 training as the weights are converted to fp16. + +- **Text Encoder (Qwen2.5-VL)**: Download from [ComfyUI's HunyuanVideo 1.5 weights](https://huggingface.co/Comfy-Org/HunyuanVideo_1.5_repackaged/tree/main). Use `split_files/text_encoders/qwen_2.5_vl_7b.safetensors`. + +- **BYT5**: Download from [ComfyUI's HunyuanVideo 1.5 weights](https://huggingface.co/Comfy-Org/HunyuanVideo_1.5_repackaged/tree/main). Use `split_files/text_encoders/byt5_small_glyphxl_fp16.safetensors`. + +For I2V training or inference, you also need: + +- **Image Encoder (SigLIP)**: Download from [ComfyUI's HunyuanVideo 1.5 weights](https://huggingface.co/Comfy-Org/HunyuanVideo_1.5_repackaged/tree/main). Use `split_files/clip_vision/sigclip_vision_patch14_384.safetensors`. + +
+日本語 + +DiT, VAE, Text Encoder (Qwen2.5-VL), BYT5 のモデルをダウンロードする必要があります。 + +- **DiT**: [HuggingFaceのHunyuanVideo 1.5のサイト](https://huggingface.co/tencent/HunyuanVideo-1.5/tree/main) からダウンロードしてください。 +I2VのDiTには`transformer/720p_i2v/diffusion_pytorch_model.safetensors`を、T2VのDiTには`transformer/720p_t2v/diffusion_pytorch_model.safetensors`を使用してください。 +[ComfyUIのHunyuanVideo 1.5用の重み](https://huggingface.co/Comfy-Org/HunyuanVideo_1.5_repackaged/tree/main)の`split_files/diffusion_models/hunyuanvideo1.5_720p_i2v_fp16.safetensors`および`split_files/diffusion_models/hunyuanvideo1.5_720p_t2v_fp16.safetensors`も使用可能ですが、重みがfp16に変換されているため、bf16学習の時には使用しないでください。 + +- **VAE**: [HuggingFaceのHunyuanVideo 1.5のサイト](https://huggingface.co/tencent/HunyuanVideo-1.5/tree/main) から `vae/diffusion_pytorch_model.safetensors` をダウンロードしてください。 +または、[ComfyUIのHunyuanVideo 1.5用の重み](https://huggingface.co/Comfy-Org/HunyuanVideo_1.5_repackaged/tree/main)の`split_files/vae/hunyuanvideo15_vae_fp16.safetensors`も使用可能です。 + +- **Text Encoder (Qwen2.5-VL)**: [ComfyUIのHunyuanVideo 1.5用の重み](https://huggingface.co/Comfy-Org/HunyuanVideo_1.5_repackaged/tree/main)から`split_files/text_encoders/qwen_2.5_vl_7b.safetensors`をダウンロードしてください。 + +- **BYT5**: [ComfyUIのHunyuanVideo 1.5用の重み](https://huggingface.co/Comfy-Org/HunyuanVideo_1.5_repackaged/tree/main)から`split_files/text_encoders/byt5_small_glyphxl_fp16.safetensors`をダウンロードしてください。 + +I2V学習または推論を行う場合は、さらに以下が必要です: + +- **Image Encoder (SigLIP)**: [ComfyUIのHunyuanVideo 1.5用の重み](https://huggingface.co/Comfy-Org/HunyuanVideo_1.5_repackaged/tree/main)から `split_files/clip_vision/sigclip_vision_patch14_384.safetensors` をダウンロードしてください。 + +
+ +## Pre-caching / 事前キャッシング + +### Latent Pre-caching / latentの事前キャッシング + +Latent pre-caching uses a dedicated script for HunyuanVideo 1.5. + +```bash +python src/musubi_tuner/hv_1_5_cache_latents.py \ + --dataset_config path/to/toml \ + --vae path/to/vae_model +``` + +- Uses `hv_1_5_cache_latents.py`. +- The dataset can be either an image dataset or a video dataset. +- `--vae_sample_size` option sets the VAE sample size for tiling. Default is 128. Set to 256 if VRAM is sufficient for better quality. Set to 0 to disable tiling (highest quality but consumes a lot of VRAM). +- `--vae_enable_patch_conv` option enables patch-based convolution in VAE for memory optimization (less effective than `--vae_sample_size`). No quality degradation. +- For I2V training, specify `--i2v` and `--image_encoder path/to/image_encoder` to cache image features and conditional latents. + +
+日本語 + +latentの事前キャッシングはHunyuanVideo 1.5専用のスクリプトを使用します。 + +- `hv_1_5_cache_latents.py`を使用します。 +- データセットは画像データセットまたは動画データセットのいずれかです。 +- `--vae_sample_size`オプションでVAEのタイリング用サンプルサイズを設定します。デフォルトは128です。VRAMが十分な場合は256に設定すると品質が向上します。0に設定するとタイリングを無効にします(最良の品質ですが非常に多くのVRAMを消費します)。 +- `--vae_enable_patch_conv`オプションでVAEのパッチベース畳み込みを有効にし、メモリを最適化します(メモリ削減効果は`--vae_sample_size`よりも落ちます)。品質の劣化はありません。 +- I2V学習の場合は、`--i2v`と`--image_encoder path/to/image_encoder`を指定して、画像の特徴と条件付きlatentをキャッシュします。 + +
+ +### Text Encoder Output Pre-caching / テキストエンコーダー出力の事前キャッシング + +Text encoder output pre-caching also uses a dedicated script. + +```bash +python src/musubi_tuner/hv_1_5_cache_text_encoder_outputs.py \ + --dataset_config path/to/toml \ + --text_encoder path/to/text_encoder \ + --byt5 path/to/byt5 \ + --batch_size 16 +``` + +- Uses `hv_1_5_cache_text_encoder_outputs.py`. +- Requires both `--text_encoder` (Qwen2.5-VL) and `--byt5` arguments. +- Use `--fp8_vl` option to run the Qwen2.5-VL Text Encoder in fp8 mode for VRAM savings. +- The larger the batch size, the more VRAM is required. Adjust `--batch_size` according to your VRAM capacity. + +
+日本語 + +テキストエンコーダー出力の事前キャッシングも専用のスクリプトを使用します。 + +- `hv_1_5_cache_text_encoder_outputs.py`を使用します。 +- `--text_encoder`(Qwen2.5-VL)と`--byt5`の両方の引数が必要です。 +- Qwen2.5-VLテキストエンコーダーをfp8モードで実行するための`--fp8_vl`オプションを使用します。 +- バッチサイズが大きいほど、より多くのVRAMが必要です。VRAM容量に応じて`--batch_size`を調整してください。 + +
+ +## Training / 学習 + +Training uses a dedicated script `hv_1_5_train_network.py`. + +### Text-to-Video (T2V) Training + +```bash +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 src/musubi_tuner/hv_1_5_train_network.py \ + --dit path/to/dit_model \ + --vae path/to/vae_model \ + --text_encoder path/to/text_encoder \ + --byt5 path/to/byt5 \ + --dataset_config path/to/toml \ + --task t2v \ + --sdpa --mixed_precision bf16 \ + --timestep_sampling shift --weighting_scheme none --discrete_flow_shift 2.0 + --optimizer_type adamw8bit --learning_rate 1e-4 --gradient_checkpointing \ + --max_data_loader_n_workers 2 --persistent_data_loader_workers \ + --network_module networks.lora_hv_1_5 --network_dim 32 \ + --max_train_epochs 16 --save_every_n_epochs 1 --seed 42 \ + --output_dir path/to/output_dir --output_name name-of-lora +``` + +### Image-to-Video (I2V) Training + +For I2V training, specify `--task i2v` and provide the `--image_encoder` path: + +```bash +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 src/musubi_tuner/hv_1_5_train_network.py \ + --dit path/to/dit_model \ + --vae path/to/vae_model \ + --text_encoder path/to/text_encoder \ + --byt5 path/to/byt5 \ + --image_encoder path/to/image_encoder \ + --dataset_config path/to/toml \ + --task i2v \ + --sdpa --mixed_precision bf16 \ + --timestep_sampling shift --weighting_scheme none --discrete_flow_shift 2.0 \ + --optimizer_type adamw8bit --learning_rate 1e-4 --gradient_checkpointing \ + --max_data_loader_n_workers 2 --persistent_data_loader_workers \ + --network_module networks.lora_hv_1_5 --network_dim 32 \ + --max_train_epochs 16 --save_every_n_epochs 1 --seed 42 \ + --output_dir path/to/output_dir --output_name name-of-lora +``` + +- Uses `hv_1_5_train_network.py`. +- **Requires** specifying `--vae`, `--text_encoder`, and `--byt5`. +- **Requires** specifying `--network_module networks.lora_hv_1_5`. +- **Requires** specifying `--task` as either `t2v` or `i2v`. +- For I2V training, `--image_encoder` is required. +- It is not yet clear whether `--mixed_precision bf16` or `fp16` is better for HunyuanVideo 1.5 training. +- The timestep sampling settings for HunyuanVideo 1.5 training are unclear, but it may be good to base them on `--timestep_sampling shift --weighting_scheme none --discrete_flow_shift 2.0` and adjust as needed. +- The recommended optimizer is `--optimizer_type Muon`, but it is only available in PyTorch 2.9 and later. If your PyTorch version is older, use `--optimizer_type adamw8bit` or similar. +- Memory saving options like `--fp8_base` and `--fp8_scaled` (for DiT) and `--fp8_vl` (for Text Encoder) are available. +- `--gradient_checkpointing` is available for memory savings. See [HunyuanVideo documentation](./hunyuan_video.md#memory-optimization) for details. + +
+日本語 + +HunyuanVideo 1.5の学習は専用のスクリプト`hv_1_5_train_network.py`を使用します。 + +**Text-to-Video (T2V) 学習** + +コマンド例は英語版を参照してください。 + +**Image-to-Video (I2V) 学習** + +I2V学習を行う場合、`--task i2v`を指定し、`--image_encoder`パスを提供します: + +コマンド例は英語版を参照してください。 + +- `hv_1_5_train_network.py`を使用します。 +- `--vae`、`--text_encoder`、`--byt5`を指定する必要があります。 +- `--network_module networks.lora_hv_1_5`を指定する必要があります。 +- `--task`に`t2v`または`i2v`を指定する必要があります。 +- I2V学習の場合は、`--image_encoder`が必要です。 +- HunyuanVideo 1.5の学習に`--mixed_precision bf16`と`fp16`のどちらが良いかはまだ不明です。 +- HunyuanVideo 1.5のタイムステップサンプリング設定は不明ですが、`--timestep_sampling shift --weighting_scheme none --discrete_flow_shift 2.0`をベースに調整すると良いかもしれません。 +- オプティマイザには`--optimizer_type Muon`を推奨しますが、PyTorch 2.9以降でのみ利用可能です。PyTorchのバージョンが古い場合は`--optimizer_type adamw8bit`などを使用してください。 +- `--fp8_base`、`--fp8_scaled`(DiT用)や`--fp8_vl`(テキストエンコーダー用)などのメモリ節約オプションが利用可能です。 +- メモリ節約のために`--gradient_checkpointing`が利用可能です。詳細は[HunyuanVideoドキュメント](./hunyuan_video.md#memory-optimization)を参照してください。 + +
+ +### Memory Optimization + +- `--fp8_base` and `--fp8_scaled` options are available to reduce memory usage of DiT (specify both together). Quality may degrade slightly. +- `--fp8_vl` option is available to reduce memory usage of Text Encoder (Qwen2.5-VL). +- `--vae_sample_size` (default 128) controls VAE tiling size. Set to 256 if VRAM is sufficient for better quality. Set to 0 to disable tiling. +- `--vae_enable_patch_conv` enables patch-based convolution in VAE for memory optimization. +- `--gradient_checkpointing` and `--gradient_checkpointing_cpu_offload` are available for memory savings. See [HunyuanVideo documentation](./hunyuan_video.md#memory-optimization) for details. +- `--blocks_to_swap` option is available to offload some blocks to CPU. The maximum number of blocks that can be offloaded is 51. + +
+日本語 + +- DiTのメモリ使用量を削減するために、`--fp8_base`と`--fp8_scaled`オプションを指定可能です(同時に指定してください)。品質はやや低下する可能性があります。 +- Text Encoder (Qwen2.5-VL)のメモリ使用量を削減するために、`--fp8_vl`オプションを指定可能です。 +- `--vae_sample_size`(デフォルト128)でVAEのタイリングサイズを制御します。VRAMが十分な場合は256に設定すると品質が向上します。0に設定するとタイリングを無効にします。 +- `--vae_enable_patch_conv`でVAEのパッチベース畳み込みを有効にし、メモリを最適化します。 +- メモリ節約のために`--gradient_checkpointing`と`--gradient_checkpointing_cpu_offload`が利用可能です。詳細は[HunyuanVideoドキュメント](./hunyuan_video.md#memory-optimization)を参照してください。 +- `--blocks_to_swap`オプションで、一部のブロックをCPUにオフロードできます。オフロード可能な最大ブロック数は51です。 + +
+ +### Attention + +- `--sdpa` for PyTorch's scaled dot product attention (does not require additional dependencies). +- `--flash_attn` for [FlashAttention](https://github.com/Dao-AILab/flash-attention). +- `--xformers` for xformers (requires `--split_attn`). +- `--sage_attn` for SageAttention (not yet supported for training). +- `--split_attn` processes attention in chunks, reducing VRAM usage slightly. + +
+日本語 + +- `--sdpa`でPyTorchのscaled dot product attentionを使用(追加の依存ライブラリを必要としません)。 +- `--flash_attn`で[FlashAttention](https://github.com/Dao-AILab/flash-attention)を使用。 +- `--xformers`でxformersの利用も可能(`--split_attn`が必要)。 +- `--sage_attn`でSageAttentionを使用(現時点では学習に未対応)。 +- `--split_attn`を指定すると、attentionを分割して処理し、VRAM使用量をわずかに減らします。 + +
+ +### Other Options + +For sample video generation during training, PyTorch Dynamo optimization, and other advanced configurations, refer to the [HunyuanVideo documentation](./hunyuan_video.md). + +
+日本語 + +学習中のサンプル動画生成、PyTorch Dynamoによる最適化、その他の高度な設定については、[HunyuanVideoドキュメント](./hunyuan_video.md)を参照してください。 + +
+ +### Coverting LoRA weights to ComfyUI format / LoRA重みをComfyUI形式に変換する + +A script is provided to convert HunyuanVideo 1.5 LoRA weights to ComfyUI format. + +```bash +python src/musubi_tuner/networks/convert_hunyuan_video_1_5_lora_to_comfy.py \ + path/to/hv_1_5_lora.safetensors \ + path/to/output_comfy_lora.safetensors +``` + +- The script is `convert_hunyuan_video_1_5_lora_to_comfy.py`. +- The first argument is the input HunyuanVideo 1.5 LoRA weights file. +- The second argument is the output ComfyUI-format LoRA weights file. +- `--reverse` option is available to convert from ComfyUI format to HunyuanVideo 1.5 format. Only works for LoRA weights converted by this script. + +
+日本語 + +HunyuanVideo 1.5のLoRA重みをComfyUI形式に変換するスクリプトが提供されています。 + +- スクリプトは`convert_hunyuan_video_1_5_lora_to_comfy.py`です。 +- 最初の引数は入力のHunyuanVideo 1.5 LoRA重みファイルです。 +- 2番目の引数は出力のComfyUI形式のLoRA重みファイルです。 +- `--reverse`オプションで、ComfyUI形式からHunyuanVideo 1.5形式への変換も可能です。このオプションは、このスクリプトで変換されたLoRA重みに対してのみ機能します。 + +
+ +## Inference / 推論 + +Inference uses a dedicated script `hv_1_5_generate_video.py`. + +The recommended number of frames is 121 and the recommended number of inference steps is 50 in the official script, but the samples below use smaller values. + +### Text-to-Video (T2V) Inference + +```bash +python src/musubi_tuner/hv_1_5_generate_video.py \ + --dit path/to/dit_model \ + --vae path/to/vae_model \ + --text_encoder path/to/text_encoder \ + --byt5 path/to/byt5 \ + --prompt "A cat" \ + --video_size 720 1280 --video_length 21 --infer_steps 25 \ + --attn_mode sdpa --fp8_scaled \ + --save_path path/to/save/dir --output_type video \ + --seed 1234 --lora_multiplier 1.0 --lora_weight path/to/lora.safetensors +``` + +### Image-to-Video (I2V) Inference + +For I2V inference, specify the `--image_path` and `--image_encoder`: + +```bash +python src/musubi_tuner/hv_1_5_generate_video.py \ + --dit path/to/dit_model \ + --vae path/to/vae_model \ + --text_encoder path/to/text_encoder \ + --byt5 path/to/byt5 \ + --image_encoder path/to/image_encoder \ + --image_path path/to/image.jpg \ + --prompt "A cat walking" \ + --video_size 720 1280 --video_length 21 --infer_steps 25 \ + --attn_mode torch --fp8_scaled \ + --save_path path/to/save/dir --output_type video \ + --seed 1234 --lora_multiplier 1.0 --lora_weight path/to/lora.safetensors +``` + +- Uses `hv_1_5_generate_video.py`. +- **Requires** specifying `--vae`, `--text_encoder`, and `--byt5`. +- For I2V inference, `--image_path` and `--image_encoder` are required. +- `--video_size` is the size of the generated video, height and width are specified in that order. +- `--video_length` should be specified as "a multiple of 4 plus 1". +- `--prompt`: Prompt for generation. +- `--fp8_scaled` option is available for DiT to reduce memory usage. Quality may be slightly lower. +- `--vae_sample_size` (default 128) controls VAE tiling size. Set to 256 if VRAM is sufficient for better quality. Set to 0 to disable tiling. +- `--vae_enable_patch_conv` enables patch-based convolution in VAE for memory optimization. +- `--blocks_to_swap` option is available to offload some blocks to CPU. The maximum number of blocks that can be offloaded is 51. +- LoRA loading options (`--lora_weight`, `--lora_multiplier`, `--include_patterns`, `--exclude_patterns`) are available. `--lycoris` is also supported. +- `--guidance_scale` (default 6.0) controls the classifier-free guidance scale. +- `--flow_shift` (default 7.0) controls the discrete flow shift. +- `--save_merged_model` option is available to save the DiT model after merging LoRA weights. Inference is skipped if this is specified. + +For 121 frames at 720p (1280x720) size, VRAM usage is around 20GB even with `--blocks_to_swap 51`. + +
+日本語 + +HunyuanVideo 1.5の推論は専用のスクリプト`hv_1_5_generate_video.py`を使用します。 + +公式スクリプトの推奨フレーム数は121、推論ステップ数は50ですが、サンプルでは少なめにしています。 + +**Text-to-Video (T2V) 推論** + +コマンド例は英語版を参照してください。 + +**Image-to-Video (I2V) 推論** + +I2V推論を行う場合、`--image_path`と`--image_encoder`を指定します: + +コマンド例は英語版を参照してください。 + +- `hv_1_5_generate_video.py`を使用します。 +- `--vae`、`--text_encoder`、`--byt5`を指定する必要があります。 +- I2V推論の場合は、`--image_path`と`--image_encoder`が必要です。 +- `--video_size`は生成する動画のサイズで、高さと幅をその順番で指定します。 +- `--video_length`は「4の倍数+1」を指定してください。 +- `--prompt`: 生成用のプロンプトです。 +- DiTのメモリ使用量を削減するために、`--fp8_scaled`オプションを指定可能です。品質はやや低下する可能性があります。 +- `--blocks_to_swap`オプションで、一部のブロックをCPUにオフロードできます。オフロード可能な最大ブロック数は51です。 +- `--vae_sample_size`(デフォルト128)でVAEのタイリングサイズを制御します。VRAMが十分な場合は256に設定すると品質が向上します。0に設定するとタイリングを無効にします。 +- `--vae_enable_patch_conv`でVAEのパッチベース畳み込みを有効にし、メモリを最適化します。 +- LoRAの読み込みオプション(`--lora_weight`、`--lora_multiplier`、`--include_patterns`、`--exclude_patterns`)が利用可能です。LyCORISもサポートされています。 +- `--guidance_scale`(デフォルト6.0)は、classifier-free guidanceスケールを制御します。 +- `--flow_shift`(デフォルト7.0)は、discrete flow shiftを制御します。 +- `--save_merged_model`オプションは、LoRAの重みをマージした後にDiTモデルを保存するためのオプションです。これを指定すると推論はスキップされます。 + +720p (1280x720) サイズで121フレームの場合、`--blocks_to_swap 51`を指定してもVRAM使用量は約20GB程度になります。 + +
diff --git a/VRGDG_Musubi-tuner/docs/kandinsky5.md b/VRGDG_Musubi-tuner/docs/kandinsky5.md new file mode 100644 index 0000000000000000000000000000000000000000..d2f248682e2df6a1a358c7887b22f271f510a4d4 --- /dev/null +++ b/VRGDG_Musubi-tuner/docs/kandinsky5.md @@ -0,0 +1,476 @@ +> 📝 Click on the language section to expand / 言語をクリックして展開 + +# Kandinsky 5 + +## Overview / 概要 + +This is an unofficial training and inference script for [Kandinsky 5](https://github.com/ai-forever/Kandinsky-5). The features are as follows: + +- fp8 support and memory reduction by block swap +- Inference without installing Flash attention (using PyTorch's scaled dot product attention) +- LoRA training for text-to-video (T2V) and image-to-video (I2V, Pro) models + +This feature is experimental. + +
+日本語 + +[Kandinsky 5](https://github.com/ai-forever/Kandinsky-5) の非公式の学習および推論スクリプトです。 + +以下の特徴があります: + +- fp8対応およびblock swapによる省メモリ化 +- Flash attentionのインストールなしでの実行(PyTorchのscaled dot product attentionを使用) +- テキストから動画(T2V)および画像から動画(I2V、Pro)モデルのLoRA学習 + +この機能は実験的なものです。 + +
+ +## Download the model / モデルのダウンロード + +Download the model weights from the [Kandinsky 5.0 Collection](https://huggingface.co/collections/ai-forever/kandinsky-50) on Hugging Face. + +### DiT Model / DiTモデル + +This document focuses on **Pro** models. The trainer also works with **Lite** models. +本ドキュメントでは **Pro** モデルを中心に説明しますが、トレーナーは **Lite** モデルでも動作します。 + +Download a Pro DiT `.safetensors` checkpoint from the Kandinsky 5.0 Collection (e.g. `kandinsky5pro_t2v_pretrain_5s.safetensors` or `kandinsky5pro_i2v_sft_5s.safetensors`). + +### VAE + +Kandinsky 5 uses the HunyuanVideo 3D VAE. Download `diffusion_pytorch_model.safetensors` (or `pytorch_model.pt`) from: +https://huggingface.co/hunyuanvideo-community/HunyuanVideo + +### Text Encoders / テキストエンコーダ + +Kandinsky 5 uses Qwen2.5-VL-7B and CLIP for text encoding. + +**Qwen2.5-VL-7B**: Download from https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct (or use the path to your local Qwen/Qwen2.5-VL-7B-Instruct model) + +**CLIP**: Use the Hugging Face Transformers model `openai/clip-vit-large-patch14`. + +Pass either the model ID (e.g., `--text_encoder_clip openai/clip-vit-large-patch14`) or a path to the locally cached snapshot directory. + +### Directory Structure / ディレクトリ構造 + +Place them in your chosen directory structure: + +``` +weights/ +├── model/ +│ └── kandinsky5pro_t2v_pretrain_5s.safetensors +├── vae/ +│ └── diffusion_pytorch_model.safetensors +├── text_encoder/ +│ └── (Qwen2.5-VL-7B files) +└── text_encoder2/ + └── (openai/clip-vit-large-patch14 files) +``` + +
+日本語 + +Hugging Faceの[Kandinsky 5.0 Collection](https://huggingface.co/collections/ai-forever/kandinsky-50)からモデルの重みをダウンロードしてください。 + +このドキュメントは **Proモデル** を前提に説明しています。 + +**DiTモデル**: 上記のリポジトリから`.safetensors`ファイルをダウンロードしてください。 + +**VAE**: Kandinsky 5はHunyuanVideo 3D VAEを使用します。上記リンクから`diffusion_pytorch_model.safetensors`(または`pytorch_model.pt`)をダウンロードしてください。 + +**テキストエンコーダ**: Qwen2.5-VL-7BとCLIPを使用します。 + +**Qwen2.5-VL-7B**: https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct からダウンロードしてください(またはローカルの `Qwen/Qwen2.5-VL-7B-Instruct` を指定します)。 + +**CLIP**: Hugging Face Transformersの `openai/clip-vit-large-patch14` を使用してください(モデルIDまたはローカルにキャッシュされたsnapshotディレクトリへのパスを指定します)。 + +任意のディレクトリ構造に配置してください。 + +
+ +## List of Kandinsky 5 models / 利用可能なタスク + +The `--task` option selects a model configuration (architecture, attention type, resolution, and default parameters). +The DiT checkpoint must be set explicitly via `--dit` (this overrides the task's default checkpoint path). + +| # | Task | Checkpoint | Parameters | HF URL | +|---|---|---|---|---| +| 1 | k5-pro-t2v-5s-sd | kandinsky5pro_t2v_sft_5s.safetensors | T2V, 5s, 19B, Pro SFT | [kandinskylab/Kandinsky-5.0-T2V-Pro-sft-5s](https://huggingface.co/kandinskylab/Kandinsky-5.0-T2V-Pro-sft-5s) | +| 2 | k5-pro-t2v-10s-sd | kandinsky5pro_t2v_sft_10s.safetensors | T2V, 10s, 19B, Pro SFT | [kandinskylab/Kandinsky-5.0-T2V-Pro-sft-10s](https://huggingface.co/kandinskylab/Kandinsky-5.0-T2V-Pro-sft-10s) | +| 3 | k5-pro-i2v-5s-sd | kandinsky5pro_i2v_sft_5s.safetensors | I2V, 5s, 19B, Pro SFT | [kandinskylab/Kandinsky-5.0-I2V-Pro-sft-5s](https://huggingface.co/kandinskylab/Kandinsky-5.0-I2V-Pro-sft-5s) | +| 4 | k5-pro-t2v-5s-sd | kandinsky5pro_t2v_pretrain_5s.safetensors | T2V, 5s, 19B, Pro Pretrain | [kandinskylab/Kandinsky-5.0-T2V-Pro-pretrain-5s](https://huggingface.co/kandinskylab/Kandinsky-5.0-T2V-Pro-pretrain-5s) | +| 5 | k5-pro-t2v-10s-sd | kandinsky5pro_t2v_pretrain_10s.safetensors | T2V, 10s, 19B, Pro Pretrain | [kandinskylab/Kandinsky-5.0-T2V-Pro-pretrain-10s](https://huggingface.co/kandinskylab/Kandinsky-5.0-T2V-Pro-pretrain-10s) | + +[Kandinsky 5.0 Video Lite models](https://huggingface.co/collections/kandinskylab/kandinsky-50-video-lite) are technically supported, but were not extensively tested. Community feedback is welcome. + +[Kandinsky 5.0 Image Lite models](https://huggingface.co/collections/kandinskylab/kandinsky-50-image-lite) are not supported, but support can be implemented if they get active support from the community. + +
+日本語 + +`--task` オプションでタスク設定(アーキテクチャ、attention、解像度、各種デフォルト値)を選択します。 +DiTのチェックポイントは `--dit` で明示的に指定できます(タスクのデフォルトのパスを上書きします)。 + +Kandinsky 5.0 Video Liteモデル(https://huggingface.co/collections/kandinskylab/kandinsky-50-video-lite)は技術的にはサポートされていますが、十分な動作確認はできていません。問題があればフィードバックをお願いします。 + +Kandinsky 5.0 Image Liteモデル(https://huggingface.co/collections/kandinskylab/kandinsky-50-image-lite)は現在サポートしていませんが、コミュニティからの継続的な要望・協力があれば対応可能です。 + +
+ +## Pre-caching / 事前キャッシュ + +Pre-caching is required before training. This involves caching both latents and text encoder outputs. + +### Notes for Kandinsky5 / Kandinsky5の注意点 + +- You must cache **text encoder outputs** with `kandinsky5_cache_text_encoder_outputs.py` before training. +- `--text_encoder_qwen` / `--text_encoder_clip` are Hugging Face Transformers models: pass a model ID (recommended) or a local HF snapshot directory. +- For I2V tasks, the latent cache stores both first and last frame latents (`latents_image`, always two frames) when running `kandinsky5_cache_latents.py`—one cache works for both first-only and first+last conditioning. + +
+日本語 + +- 学習前に、`kandinsky5_cache_text_encoder_outputs.py` による **テキストエンコーダ出力のキャッシュ** が必須です。 +- `--text_encoder_qwen` / `--text_encoder_clip` はHugging Face Transformersのモデルです。モデルID(推奨)またはローカルのHF snapshotディレクトリを指定してください。 +- I2Vタスクでは、`kandinsky5_cache_latents.py` 実行時に最初と最後のフレームlatent(`latents_image`、常に2フレーム)もキャッシュされます。1回のキャッシュで first / first+last 両方のモードに対応できます。 + +
+ +### Text Encoder Output Pre-caching / テキストエンコーダ出力の事前キャッシュ + +Text encoder output pre-caching is required. Create the cache using the following command: + +```bash +python kandinsky5_cache_text_encoder_outputs.py \ + --dataset_config path/to/dataset.toml \ + --text_encoder_qwen Qwen/Qwen2.5-VL-7B-Instruct \ + --text_encoder_clip openai/clip-vit-large-patch14 \ + --batch_size 4 +``` + +Adjust `--batch_size` according to your available VRAM. + +For additional options, use `python kandinsky5_cache_text_encoder_outputs.py --help`. + +
+日本語 + +テキストエンコーダ出力の事前キャッシュは必須です。上のコマンド例を使用してキャッシュを作成してください。 + +使用可能なVRAMに合わせて `--batch_size` を調整してください。 + +その他のオプションは `--help` で確認できます。 + +
+ +### Latent Pre-caching / latentの事前キャッシュ + +Latent pre-caching is required. Create the cache using the following command: + +```bash +python kandinsky5_cache_latents.py \ + --dataset_config path/to/dataset.toml \ + --vae path/to/vae/diffusion_pytorch_model.safetensors +``` + +For NABLA training, you may want to build NABLA-compatible latent caches: + +```bash +python kandinsky5_cache_latents.py \ + --dataset_config path/to/dataset.toml \ + --vae path/to/vae/diffusion_pytorch_model.safetensors \ + --nabla_resize +``` + +If you're running low on VRAM, lower the `--batch_size`. + +For additional options, use `python kandinsky5_cache_latents.py --help`. + +
+日本語 + +latentの事前キャッシュは必須です。上のコマンド例を使用してキャッシュを作成してください。 + +VRAMが足りない場合は、`--batch_size`を小さくしてください。 + +NABLAで学習する場合は、NABLA互換のlatentキャッシュを作成することを推奨します: + +```bash +python kandinsky5_cache_latents.py \ + --dataset_config path/to/dataset.toml \ + --vae path/to/vae/diffusion_pytorch_model.safetensors \ + --nabla_resize +``` + +その他のオプションは `--help` で確認できます。 + +
+ +## Training / 学習 + +Start training using the following command (input as a single line): + +```bash +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 \ + kandinsky5_train_network.py \ + --mixed_precision bf16 \ + --dataset_config path/to/dataset.toml \ + --task k5-pro-t2v-5s-sd \ + --dit path/to/kandinsky5pro_t2v_pretrain_5s.safetensors \ + --text_encoder_qwen Qwen/Qwen2.5-VL-7B-Instruct \ + --text_encoder_clip openai/clip-vit-large-patch14 \ + --vae path/to/vae/diffusion_pytorch_model.safetensors \ + --fp8_base \ + --sdpa \ + --gradient_checkpointing \ + --max_data_loader_n_workers 1 \ + --persistent_data_loader_workers \ + --learning_rate 1e-4 \ + --optimizer_type AdamW8Bit \ + --optimizer_args "weight_decay=0.001" "betas=(0.9,0.95)" \ + --max_grad_norm 1.0 \ + --lr_scheduler constant_with_warmup \ + --lr_warmup_steps 100 \ + --network_module networks.lora_kandinsky \ + --network_dim 32 \ + --network_alpha 32 \ + --timestep_sampling shift \ + --discrete_flow_shift 5.0 \ + --output_dir path/to/output \ + --output_name k5_lora \ + --save_every_n_epochs 1 \ + --max_train_epochs 50 \ + --scheduler_scale 10.0 +``` + +For I2V training, switch the task and checkpoint to an I2V preset (e.g., `k5-pro-i2v-5s-sd` with `kandinsky5pro_i2v_sft_5s.safetensors`). The latent cache already stores first and last frame latents (`latents_image`, two frames) when you run `kandinsky5_cache_latents.py`, so the same cache covers both first-only and first+last modes—no extra flags are needed beyond picking an I2V task. + +**Note on first+last frame conditioning**: First+last frame training support is experimental. The effectiveness and plausibility of this approach have not yet been thoroughly tested. Feedback and results from community testing are welcome. + +The training settings are experimental. Appropriate learning rates, training steps, timestep distribution, etc. are not yet fully determined. Feedback is welcome. + +For additional options, use `python kandinsky5_train_network.py --help`. + +### Key Options / 主要オプション + +- `--task`: Model configuration (architecture, attention type, resolution, sampling parameters). See Available Tasks above. +- `--dit`: Path to DiT checkpoint. **Overrides the task's default checkpoint path.** You can use any compatible checkpoint (SFT, pretrain, or your own) with any task config as long as the architecture matches. +- `--vae`: Path to VAE checkpoint (overrides task default) +- `--network_module`: Use `networks.lora_kandinsky` for Kandinsky5 LoRA + +**Note**: The `--task` option only sets the model architecture and parameters, not the weights. Use `--dit` to specify which checkpoint to load. + +**注意**: `--task`オプションはモデルのアーキテクチャとパラメータのみを設定し、重みは設定しません。`--dit`で読み込むチェックポイントを指定してください。 + +### Memory Optimization / メモリ最適化 + +`--gradient_checkpointing` enables gradient checkpointing to reduce VRAM usage. + +`--fp8_base` runs DiT in fp8 mode. This can significantly reduce memory consumption but may impact output quality. + +If you're running low on VRAM, use `--blocks_to_swap` to offload some blocks to CPU. + +`--gradient_checkpointing_cpu_offload` can be used to offload activations to CPU when using gradient checkpointing. This must be used together with `--gradient_checkpointing`. + +### Attention / アテンション + +Use `--sdpa`, `--flash_attn`, `--flash3`, `--sage_attn`, or `--xformers` to control the attention backend for Kandinsky5. + +### Kandinsky5-specific Options / Kandinsky5固有オプション + +- `--scheduler_scale`: Overrides the task's scheduler scaling factor. This affects the timestep schedule used in sampling/inference and is also stored in the task config used during training. +- `--offload_dit_during_sampling`: Offloads the DiT model to CPU during sampling (sample generation during training, and in `kandinsky5_generate_video.py`) to reduce peak VRAM usage. +- `--i` / `--image`: Init image path for i2v-style seeding in `kandinsky5_generate_video.py`. + +**NABLA attention (training):** + +- `--force_nabla_attention`: Force NABLA attention regardless of the task default. +- `--nabla_method`: NABLA binarization method (default `topcdf`). +- `--nabla_P`: CDF threshold (default `0.9`). +- `--nabla_wT`, `--nabla_wH`, `--nabla_wW`: STA window sizes (defaults `11`, `3`, `3`). +- `--nabla_add_sta` / `--no_nabla_add_sta`: Enable/disable STA prior when forcing NABLA. + +**NABLA-compatible latent caching:** + +- `kandinsky5_cache_latents.py --nabla_resize`: Resizes inputs to the next multiple of 128 before VAE encoding, which helps produce latents compatible with NABLA geometry constraints. + +### Sample Generation During Training / 学習中のサンプル生成 + +Sample generation during training is supported. See [sampling during training](./sampling_during_training.md) for details. + +
+日本語 + +上のコマンド例を使用して学習を開始してください(実際には一行で入力)。 + +日本語セクションの例(英語セクションと同じ内容): + +```bash +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 \ + kandinsky5_train_network.py \ + --mixed_precision bf16 \ + --dataset_config path/to/dataset.toml \ + --task k5-pro-t2v-5s-sd \ + --dit path/to/kandinsky5pro_t2v_pretrain_5s.safetensors \ + --text_encoder_qwen Qwen/Qwen2.5-VL-7B-Instruct \ + --text_encoder_clip openai/clip-vit-large-patch14 \ + --vae path/to/vae/diffusion_pytorch_model.safetensors \ + --fp8_base \ + --sdpa \ + --gradient_checkpointing \ + --max_data_loader_n_workers 1 \ + --persistent_data_loader_workers \ + --learning_rate 1e-4 \ + --optimizer_type AdamW8Bit \ + --optimizer_args "weight_decay=0.001" "betas=(0.9,0.95)" \ + --max_grad_norm 1.0 \ + --lr_scheduler constant_with_warmup \ + --lr_warmup_steps 100 \ + --network_module networks.lora_kandinsky \ + --network_dim 32 \ + --network_alpha 32 \ + --timestep_sampling shift \ + --discrete_flow_shift 5.0 \ + --output_dir path/to/output \ + --output_name k5_lora \ + --save_every_n_epochs 1 \ + --max_train_epochs 50 \ + --scheduler_scale 10.0 +``` + +I2Vの学習を行う場合は、タスクとチェックポイントをI2V向けプリセットに変更してください(例: `k5-pro-i2v-5s-sd` と `kandinsky5pro_i2v_sft_5s.safetensors`)。`kandinsky5_cache_latents.py` でlatentをキャッシュする際に、最初のフレームlatent(`latents_image`)も保存されるため、I2V専用の追加フラグは不要です(I2Vタスクを選ぶだけで動作します)。 + +**最初と最後のフレーム条件付けについて**: 最初と最後のフレーム学習サポートは実験的なものです。このアプローチの有効性と妥当性はまだ十分にテストされていません。コミュニティからのフィードバックと結果をお待ちしています。 + +学習設定は実験的なものです。適切な学習率、学習ステップ数、タイムステップの分布などは、まだ完全には決まっていません。フィードバックをお待ちしています。 + +その他のオプションは `--help` で確認できます。 + +**主要オプション** + +- `--task`: モデル設定(上記の利用可能なタスクを参照) +- `--dit`: DiTチェックポイントへのパス(タスクのデフォルトを上書き) +- `--vae`: VAEチェックポイントへのパス(タスクのデフォルトを上書き) +- `--network_module`: Kandinsky5 LoRAには `networks.lora_kandinsky` を使用 + +**メモリ最適化** + +`--gradient_checkpointing`でgradient checkpointingを有効にし、VRAM使用量を削減できます。 + +`--fp8_base`を指定すると、DiTがfp8で学習されます。消費メモリを大きく削減できますが、品質は低下する可能性があります。 + +VRAMが足りない場合は、`--blocks_to_swap`を指定して、一部のブロックをCPUにオフロードしてください。 + +`--gradient_checkpointing_cpu_offload`を指定すると、gradient checkpointing使用時にアクティベーションをCPUにオフロードします。`--gradient_checkpointing`と併用する必要があります。 + +**アテンション** + +`--sdpa`/`--flash_attn`/`--flash3`/`--sage_attn`/`--xformers`はKandinsky5のattention backendに適用されます。 + +**Kandinsky5固有オプション** + +- `--scheduler_scale`: タスクの`scheduler_scale`を上書きします。サンプリング/推論で使うタイムステップスケジュールに影響します。 +- `--offload_dit_during_sampling`: サンプル生成時(学習中のサンプリング、および `kandinsky5_generate_video.py`)にDiTをCPUへ退避し、ピークVRAMを下げます。 +- `--i` / `--image`: `kandinsky5_generate_video.py` でi2v風の初期画像(1フレーム目のシード)を指定します。 + +**NABLAアテンション(学習)** + +- `--force_nabla_attention`: タスク設定に関係なくNABLAを強制します。 +- `--nabla_method`: NABLAの二値化メソッド(デフォルト `topcdf`)。 +- `--nabla_P`: CDFしきい値(デフォルト `0.9`)。 +- `--nabla_wT`, `--nabla_wH`, `--nabla_wW`: STAウィンドウ(デフォルト `11`, `3`, `3`)。 +- `--nabla_add_sta` / `--no_nabla_add_sta`: STA priorの有効/無効。 + +**NABLA互換latentキャッシュ** + +- `kandinsky5_cache_latents.py --nabla_resize`: VAEエンコード前に入力を128の倍数へリサイズし、NABLAの幾何条件に合うlatentを生成しやすくします。 + +**学習中のサンプル生成** + +学習中のサンプル生成がサポートされています。詳細は[学習中のサンプリング](./sampling_during_training.md)を参照してください。 + +
+ +## Inference / 推論 + +Generate videos using the following command: + +```bash +python kandinsky5_generate_video.py \ + --task k5-pro-t2v-5s-sd \ + --dit path/to/kandinsky5pro_t2v_pretrain_5s.safetensors \ + --vae path/to/vae/diffusion_pytorch_model.safetensors \ + --text_encoder_qwen Qwen/Qwen2.5-VL-7B-Instruct \ + --text_encoder_clip openai/clip-vit-large-patch14 \ + --offload_dit_during_sampling \ + --fp8_base \ + --dtype bfloat16 \ + --prompt "A cat walks on the grass, realistic style." \ + --negative_prompt "low quality, artifacts" \ + --frames 17 \ + --steps 50 \ + --guidance 5 \ + --scheduler_scale 10 \ + --seed 42 \ + --width 512 \ + --height 512 \ + --output path/to/output.mp4 \ + --lora_weight path/to/lora.safetensors \ + --lora_multiplier 1.0 +``` + +### Options / オプション + +- `--task`: Model configuration +- `--prompt`: Text prompt for generation +- `--negative_prompt`: Negative prompt (optional) +- `--output`: Output file path (.mp4 for video, .png for image) +- `--width`, `--height`: Output resolution (defaults from task config) +- `--frames`: Number of frames (defaults from task config) +- `--steps`: Number of inference steps (defaults from task config) +- `--guidance`: Guidance scale (defaults from task config) +- `--seed`: Random seed +- `--fp8_base`: Run DiT in fp8 mode +- `--blocks_to_swap`: Number of blocks to offload to CPU +- `--lora_weight`: Path(s) to LoRA weight file(s) +- `--lora_multiplier`: LoRA multiplier(s) + +For additional options, use `python kandinsky5_generate_video.py --help`. + +
+日本語 + +上のコマンド例を使用して動画を生成します。 + +**オプション** + +- `--task`: モデル設定 +- `--prompt`: 生成用のテキストプロンプト +- `--negative_prompt`: ネガティブプロンプト(オプション) +- `--output`: 出力ファイルパス(動画は.mp4、画像は.png) +- `--width`, `--height`: 出力解像度(タスク設定からのデフォルト) +- `--frames`: フレーム数(タスク設定からのデフォルト) +- `--steps`: 推論ステップ数(タスク設定からのデフォルト) +- `--guidance`: ガイダンススケール(タスク設定からのデフォルト) +- `--seed`: ランダムシード +- `--fp8_base`: DiTをfp8モードで実行 +- `--blocks_to_swap`: CPUにオフロードするブロック数 +- `--lora_weight`: LoRA重みファイルへのパス +- `--lora_multiplier`: LoRA係数 + +その他のオプションは `--help` で確認できます。 + +
+ +## Dataset Configuration / データセット設定 + +Dataset configuration is the same as other architectures. See [dataset configuration](./dataset_config.md) for details. + +
+日本語 + +データセット設定は他のアーキテクチャと同じです。詳細は[データセット設定](./dataset_config.md)を参照してください。 + +
diff --git a/VRGDG_Musubi-tuner/docs/kisekaeichi_ref.png b/VRGDG_Musubi-tuner/docs/kisekaeichi_ref.png new file mode 100644 index 0000000000000000000000000000000000000000..b3c97e632672364b360c6a26d2bc251dcf485dd8 --- /dev/null +++ b/VRGDG_Musubi-tuner/docs/kisekaeichi_ref.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e5037f0a0cfb1a6b0a8d1f19fb462df75fb53384d0d9e654c359ca984fafa605 +size 583507 diff --git a/VRGDG_Musubi-tuner/docs/kisekaeichi_ref_mask.png b/VRGDG_Musubi-tuner/docs/kisekaeichi_ref_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..f3017bc9c4ff921381ddfd4a3f4da3be194510c8 --- /dev/null +++ b/VRGDG_Musubi-tuner/docs/kisekaeichi_ref_mask.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:69ebba82dd24ff20b0c60cbb0a6d32e879dee36a58c6ca35867862c3a5c407a4 +size 17351 diff --git a/VRGDG_Musubi-tuner/docs/kisekaeichi_result.png b/VRGDG_Musubi-tuner/docs/kisekaeichi_result.png new file mode 100644 index 0000000000000000000000000000000000000000..52c13c39df20aee7b405e5faa64104ea0c4c641f --- /dev/null +++ b/VRGDG_Musubi-tuner/docs/kisekaeichi_result.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:223dacb98ac834a442ee124641a6b852b1cde3bc1f11939e78192fc8be2f7b49 +size 408282 diff --git a/VRGDG_Musubi-tuner/docs/kisekaeichi_start.png b/VRGDG_Musubi-tuner/docs/kisekaeichi_start.png new file mode 100644 index 0000000000000000000000000000000000000000..b31c37500db6083aa54b1c6b868cb8a56d928745 --- /dev/null +++ b/VRGDG_Musubi-tuner/docs/kisekaeichi_start.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:beee4a910402ef2798b00aa4d193b0b7186380ed24928a4d39acc8635d2cfdaf +size 1033975 diff --git a/VRGDG_Musubi-tuner/docs/kisekaeichi_start_mask.png b/VRGDG_Musubi-tuner/docs/kisekaeichi_start_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..0a775dd6af68f4674dbf06fcc44b30210f445d13 --- /dev/null +++ b/VRGDG_Musubi-tuner/docs/kisekaeichi_start_mask.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9e81933caf5125439e46a34476d339912b981d868517e278d6f9fb6064b328c6 +size 14908 diff --git a/VRGDG_Musubi-tuner/docs/logsnr_distribution.png b/VRGDG_Musubi-tuner/docs/logsnr_distribution.png new file mode 100644 index 0000000000000000000000000000000000000000..a5b14349426063ba4e608f32924069f4aac35dbc --- /dev/null +++ b/VRGDG_Musubi-tuner/docs/logsnr_distribution.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a612d0570c3a4cf6a0ea75be934f7d6ced788d5e58c0e9dcbfcc16ce5487c50a +size 15186 diff --git a/VRGDG_Musubi-tuner/docs/loha_lokr.md b/VRGDG_Musubi-tuner/docs/loha_lokr.md new file mode 100644 index 0000000000000000000000000000000000000000..ff46ae6506241b2d636432b01f2a52beeacdbf39 --- /dev/null +++ b/VRGDG_Musubi-tuner/docs/loha_lokr.md @@ -0,0 +1,341 @@ +> 📝 Click on the language section to expand / 言語をクリックして展開 + +# LoHa / LoKr (LyCORIS) + +## Overview / 概要 + +In addition to standard LoRA, Musubi Tuner supports **LoHa** (Low-rank Hadamard Product) and **LoKr** (Low-rank Kronecker Product) as alternative parameter-efficient fine-tuning methods. These are based on techniques from the [LyCORIS](https://github.com/KohakuBlueleaf/LyCORIS) project. + +- **LoHa**: Represents weight updates as a Hadamard (element-wise) product of two low-rank matrices. Reference: [FedPara (arXiv:2108.06098)](https://arxiv.org/abs/2108.06098) +- **LoKr**: Represents weight updates as a Kronecker product with optional low-rank decomposition. Reference: [LoKr (arXiv:2309.14859)](https://arxiv.org/abs/2309.14859) + +The algorithms and recommended settings are described in the [LyCORIS documentation](https://github.com/KohakuBlueleaf/LyCORIS/blob/main/docs/Algo-List.md) and [guidelines](https://github.com/KohakuBlueleaf/LyCORIS/blob/main/docs/Guidelines.md). + +Both methods target Linear layers only (Conv2d layers are not supported in this implementation). + +This feature is experimental. + +
+日本語 + +Musubi Tunerでは、標準的なLoRAに加え、代替のパラメータ効率の良いファインチューニング手法として **LoHa**(Low-rank Hadamard Product)と **LoKr**(Low-rank Kronecker Product)をサポートしています。これらは [LyCORIS](https://github.com/KohakuBlueleaf/LyCORIS) プロジェクトの手法に基づいています。 + +- **LoHa**: 重みの更新を2つの低ランク行列のHadamard積(要素ごとの積)で表現します。参考文献: [FedPara (arXiv:2108.06098)](https://arxiv.org/abs/2108.06098) +- **LoKr**: 重みの更新をKronecker積と、オプションの低ランク分解で表現します。参考文献: [LoKr (arXiv:2309.14859)](https://arxiv.org/abs/2309.14859) + +アルゴリズムと推奨設定は[LyCORISのアルゴリズム解説](https://github.com/KohakuBlueleaf/LyCORIS/blob/main/docs/Algo-List.md)と[ガイドライン](https://github.com/KohakuBlueleaf/LyCORIS/blob/main/docs/Guidelines.md)を参照してください。 + +いずれもLinear層のみを対象としています(Conv2d層はこの実装ではサポートしていません)。 + +この機能は実験的なものです。 + +
+ +## Acknowledgments / 謝辞 + +The LoHa and LoKr implementations in Musubi Tuner are based on the [LyCORIS](https://github.com/KohakuBlueleaf/LyCORIS) project by [KohakuBlueleaf](https://github.com/KohakuBlueleaf). We would like to express our sincere gratitude for the excellent research and open-source contributions that made this implementation possible. + +
+日本語 + +Musubi TunerのLoHaおよびLoKrの実装は、[KohakuBlueleaf](https://github.com/KohakuBlueleaf)氏による[LyCORIS](https://github.com/KohakuBlueleaf/LyCORIS)プロジェクトに基づいています。この実装を可能にしてくださった素晴らしい研究とオープンソースへの貢献に心から感謝いたします。 + +
+ +## Supported architectures / 対応アーキテクチャ + +LoHa and LoKr automatically detect the model architecture and apply appropriate default settings. The following architectures are supported: + +- HunyuanVideo +- HunyuanVideo 1.5 +- Wan 2.1/2.2 +- FramePack +- FLUX.1 Kontext / FLUX.2 +- Qwen-Image series +- Z-Image + +Kandinsky5 is **not supported** with LoHa/LoKr (it requires special handling that is incompatible with automatic architecture detection). + +Each architecture has its own default `exclude_patterns` to skip non-trainable modules (e.g., modulation layers, normalization layers). These are applied automatically when using LoHa/LoKr. + +
+日本語 + +LoHaとLoKrは、モデルのアーキテクチャを自動で検出し、適切なデフォルト設定を適用します。以下のアーキテクチャに対応しています: + +- HunyuanVideo +- HunyuanVideo 1.5 +- Wan 2.1/2.2 +- FramePack +- FLUX.1 Kontext / FLUX.2 +- Qwen-Image系 +- Z-Image + +Kandinsky5はLoHa/LoKrに **対応していません**(自動アーキテクチャ検出と互換性のない特殊な処理が必要です)。 + +各アーキテクチャには、学習対象外のモジュール(modulation層、normalization層など)をスキップするデフォルトの `exclude_patterns` が設定されています。LoHa/LoKr使用時にはこれらが自動的に適用されます。 + +
+ +## Training / 学習 + +To use LoHa or LoKr, change the `--network_module` argument in your training command. All other training options (dataset config, optimizer, etc.) remain the same as LoRA. + +
+日本語 + +LoHaまたはLoKrを使用するには、学習コマンドの `--network_module` 引数を変更します。その他の学習オプション(データセット設定、オプティマイザなど)はLoRAと同じです。 + +
+ +### LoHa + +```bash +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 src/musubi_tuner/hv_train_network.py \ + --dit path/to/dit \ + --dataset_config path/to/toml \ + --sdpa --mixed_precision bf16 --fp8_base \ + --optimizer_type adamw8bit --learning_rate 2e-4 --gradient_checkpointing \ + --network_module networks.loha --network_dim 32 --network_alpha 16 \ + --max_train_epochs 16 --save_every_n_epochs 1 \ + --output_dir path/to/output --output_name my-loha +``` + +### LoKr + +```bash +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 src/musubi_tuner/hv_train_network.py \ + --dit path/to/dit \ + --dataset_config path/to/toml \ + --sdpa --mixed_precision bf16 --fp8_base \ + --optimizer_type adamw8bit --learning_rate 2e-4 --gradient_checkpointing \ + --network_module networks.lokr --network_dim 32 --network_alpha 16 \ + --max_train_epochs 16 --save_every_n_epochs 1 \ + --output_dir path/to/output --output_name my-lokr +``` + +Replace `hv_train_network.py` with the appropriate training script for your architecture (e.g., `wan_train_network.py`, `fpack_train_network.py`, etc.). + +
+日本語 + +`hv_train_network.py` の部分は、お使いのアーキテクチャに対応する学習スクリプト(`wan_train_network.py`, `fpack_train_network.py` など)に置き換えてください。 + +
+ +### Common training options / 共通の学習オプション + +The following `--network_args` options are available for both LoHa and LoKr, same as LoRA: + +| Option | Description | +|---|---| +| `verbose=True` | Display detailed information about the network modules | +| `rank_dropout=0.1` | Apply dropout to the rank dimension during training | +| `module_dropout=0.1` | Randomly skip entire modules during training | +| `exclude_patterns=[r'...']` | Exclude modules matching the regex patterns (in addition to architecture defaults) | +| `include_patterns=[r'...']` | Include only modules matching the regex patterns | + +See [Advanced configuration](advanced_config.md) for details on how to specify `network_args`. + +
+日本語 + +以下の `--network_args` オプションは、LoRAと同様にLoHaとLoKrの両方で使用できます: + +| オプション | 説明 | +|---|---| +| `verbose=True` | ネットワークモジュールの詳細情報を表示 | +| `rank_dropout=0.1` | 学習時にランク次元にドロップアウトを適用 | +| `module_dropout=0.1` | 学習時にモジュール全体をランダムにスキップ | +| `exclude_patterns=[r'...']` | 正規表現パターンに一致するモジュールを除外(アーキテクチャのデフォルトに追加) | +| `include_patterns=[r'...']` | 正規表現パターンに一致するモジュールのみを対象とする | + +`network_args` の指定方法の詳細は [高度な設定](advanced_config.md) を参照してください。 + +
+ +### LoKr-specific option: `factor` / LoKr固有のオプション: `factor` + +LoKr decomposes weight dimensions using factorization. The `factor` option controls how dimensions are split: + +- `factor=-1` (default): Automatically find balanced factors. For example, dimension 512 is split into (16, 32). +- `factor=N` (positive integer): Force factorization using the specified value. For example, `factor=4` splits dimension 512 into (4, 128). + +```bash +--network_args "factor=4" +``` + +When `network_dim` (rank) is large enough relative to the factorized dimensions, LoKr uses a full matrix instead of a low-rank decomposition for the second factor. A warning will be logged in this case. + +
+日本語 + +LoKrは重みの次元を因数分解して分割します。`factor` オプションでその分割方法を制御します: + +- `factor=-1`(デフォルト): バランスの良い因数を自動的に見つけます。例えば、次元512は(16, 32)に分割されます。 +- `factor=N`(正の整数): 指定した値で因数分解します。例えば、`factor=4` は次元512を(4, 128)に分割します。 + +```bash +--network_args "factor=4" +``` + +`network_dim`(ランク)が因数分解された次元に対して十分に大きい場合、LoKrは第2因子に低ランク分解ではなくフル行列を使用します。その場合、警告がログに出力されます。 + +
+ +## How LoHa and LoKr work / LoHaとLoKrの仕組み + +### LoHa + +LoHa represents the weight update as a Hadamard (element-wise) product of two low-rank matrices: + +``` +ΔW = (W1a × W1b) ⊙ (W2a × W2b) +``` + +where `W1a`, `W1b`, `W2a`, `W2b` are low-rank matrices with rank `network_dim`. This means LoHa has roughly **twice the number of trainable parameters** compared to LoRA at the same rank, but can capture more complex weight structures due to the element-wise product. + +### LoKr + +LoKr represents the weight update using a Kronecker product: + +``` +ΔW = W1 ⊗ W2 (where W2 = W2a × W2b in low-rank mode) +``` + +The original weight dimensions are factorized (e.g., a 512×512 weight might be split so that W1 is 16×16 and W2 is 32×32). W1 is always a full matrix (small), while W2 can be either low-rank decomposed or a full matrix depending on the rank setting. LoKr tends to produce **smaller models** compared to LoRA at the same rank. + +
+日本語 + +### LoHa + +LoHaは重みの更新を2つの低ランク行列のHadamard積(要素ごとの積)で表現します: + +``` +ΔW = (W1a × W1b) ⊙ (W2a × W2b) +``` + +ここで `W1a`, `W1b`, `W2a`, `W2b` はランク `network_dim` の低ランク行列です。LoHaは同じランクのLoRAと比較して学習可能なパラメータ数が **約2倍** になりますが、要素ごとの積により、より複雑な重み構造を捉えることができます。 + +### LoKr + +LoKrはKronecker積を使って重みの更新を表現します: + +``` +ΔW = W1 ⊗ W2 (低ランクモードでは W2 = W2a × W2b) +``` + +元の重みの次元が因数分解されます(例: 512×512の重みが、W1が16×16、W2が32×32に分割されます)。W1は常にフル行列(小さい)で、W2はランク設定に応じて低ランク分解またはフル行列になります。LoKrは同じランクのLoRAと比較して **より小さいモデル** を生成する傾向があります。 + +
+ +## Inference / 推論 + +Trained LoHa/LoKr weights are saved in safetensors format, just like LoRA. The inference method depends on the architecture. + +
+日本語 + +学習済みのLoHa/LoKrの重みは、LoRAと同様にsafetensors形式で保存されます。推論方法はアーキテクチャによって異なります。 + +
+ +### Architectures with built-in support / ネイティブサポートのあるアーキテクチャ + +The following architectures automatically detect and load LoHa/LoKr weights without any additional options: + +- Wan 2.1/2.2 +- FramePack +- HunyuanVideo 1.5 +- FLUX.2 +- Qwen-Image series +- Z-Image + +Use `--lora_weight` as usual: + +```bash +python src/musubi_tuner/wan_generate_video.py ... --lora_weight path/to/loha_or_lokr.safetensors +``` + +
+日本語 + +以下のアーキテクチャでは、LoHa/LoKrの重みを追加オプションなしで自動検出して読み込みます: + +- Wan 2.1/2.2 +- FramePack +- HunyuanVideo 1.5 +- FLUX.2 +- Qwen-Image系 +- Z-Image + +通常通り `--lora_weight` を使用します: + +```bash +python src/musubi_tuner/wan_generate_video.py ... --lora_weight path/to/loha_or_lokr.safetensors +``` + +
+ +### HunyuanVideo / FLUX.1 Kontext + +For HunyuanVideo and FLUX.1 Kontext, the `--lycoris` option is required, and the [LyCORIS library](https://github.com/KohakuBlueleaf/LyCORIS) must be installed: + +```bash +pip install lycoris-lora + +python src/musubi_tuner/hv_generate_video.py ... --lora_weight path/to/loha_or_lokr.safetensors --lycoris +``` + +
+日本語 + +HunyuanVideoとFLUX.1 Kontextでは、`--lycoris` オプションが必要で、[LyCORIS ライブラリ](https://github.com/KohakuBlueleaf/LyCORIS)のインストールが必要です: + +```bash +pip install lycoris-lora + +python src/musubi_tuner/hv_generate_video.py ... --lora_weight path/to/loha_or_lokr.safetensors --lycoris +``` + +
+ +## Limitations / 制限事項 + +### LoRA+ is not supported / LoRA+は非対応 + +LoRA+ (`loraplus_lr_ratio` in `--network_args`) is **not supported** with LoHa/LoKr. LoRA+ works by applying different learning rates to the LoRA-A and LoRA-B matrices, which is specific to the standard LoRA architecture. LoHa and LoKr have different parameter structures and this optimization does not apply. + +
+日本語 + +LoRA+(`--network_args` の `loraplus_lr_ratio`)はLoHa/LoKrでは **非対応** です。LoRA+はLoRA-AとLoRA-Bの行列に異なる学習率を適用する手法であり、標準的なLoRAのアーキテクチャに固有のものです。LoHaとLoKrはパラメータ構造が異なるため、この最適化は適用されません。 + +
+ +### Merging to base model / ベースモデルへのマージ + +`merge_lora.py` currently supports standard LoRA only. LoHa/LoKr weights cannot be merged into the base model using this script. + +For architectures with built-in LoHa/LoKr support (listed above), merging is performed automatically during model loading at inference time, so this limitation only affects offline merging workflows. + +
+日本語 + +`merge_lora.py` は現在、標準LoRAのみをサポートしています。このスクリプトではLoHa/LoKrの重みをベースモデルにマージすることはできません。 + +LoHa/LoKrのネイティブサポートがあるアーキテクチャ(上記)では、推論時のモデル読み込み時にマージが自動的に行われるため、この制限はオフラインマージのワークフローにのみ影響します。 + +
+ +### Format conversion / フォーマット変換 + +`convert_lora.py` is extended to also support format conversion of LoHa/LoKr weights between Musubi Tuner format and Diffusers format for ComfyUI. + +
+日本語 + +`convert_lora.py` は、LoRAに加えて、LoHa/LoKrの重みのフォーマット変換(Musubi Tuner形式とDiffusers形式間の変換)についてもサポートするよう、拡張されています。 + +
diff --git a/VRGDG_Musubi-tuner/docs/ltx_2.md b/VRGDG_Musubi-tuner/docs/ltx_2.md new file mode 100644 index 0000000000000000000000000000000000000000..a70418b484f91f7209028056642c55efbf1049ac --- /dev/null +++ b/VRGDG_Musubi-tuner/docs/ltx_2.md @@ -0,0 +1,3031 @@ +# LTX-2 / LTX-2.3 + +Supports LoRA training for both **LTX-2 (19B)** and **LTX-2.3 (22B)** models with the following training modes: text-to-video, joint audio-video, audio-only, IC-LoRA / video-to-video, and audio-reference IC-LoRA. + +### Supported Model Versions + +| Version | Parameters | Key Differences | +|---------|-----------|-----------------| +| LTX-2 (19B) | 19B | Single `aggregate_embed`, caption projection inside transformer | +| LTX-2.3 (22B) | 22B | Dual `video_aggregate_embed`/`audio_aggregate_embed`, caption projection moved to feature extractor (`caption_proj_before_connector`), cross-attention AdaLN (`prompt_adaln`), separate audio connector dimensions, BigVGAN v2 vocoder with bandwidth extension | + +Version choice for training is controlled by `--ltx_version` (default: `2.3`) in `ltx2_train_network.py`. The trainer auto-detects the checkpoint version from metadata and warns on mismatch. + +Caching scripts (`ltx2_cache_latents.py`, `ltx2_cache_text_encoder_outputs.py`) also accept `--ltx_version`, but only for sample-prompt precaching defaults (`--precache_sample_latents` / `--precache_sample_prompts`). Dataset cache compatibility is still driven by `--ltx2_checkpoint` and `--ltx2_mode`. + +--- + +## Table of Contents + +- [Installation](#installation) + - [CUDA Version](#cuda-version) + - [Downloading Required Models](#downloading-required-models) +- [Supported Model Versions](#supported-model-versions) +- [Supported Dataset Types](#supported-dataset-types) +- [1. Caching Latents](#1-caching-latents) + - [Latent Caching Command](#latent-caching-command) + - [Latent Caching Arguments](#latent-caching-arguments) + - [Latent Cache Output Files](#latent-cache-output-files) + - [Memory Optimization for Caching](#memory-optimization-for-caching) +- [2. Caching Text Encoder Outputs](#2-caching-text-encoder-outputs) + - [Text Encoder Caching Command](#text-encoder-caching-command) + - [Text Encoder Caching Arguments](#text-encoder-caching-arguments) + - [Text Encoder Output Files](#text-encoder-output-files) + - [Loading Gemma from a Single Safetensors File](#loading-gemma-from-a-single-safetensors-file) +- [3. Training](#3-training) + - [Choosing Model Version for Training (2.0 vs 2.3)](#choosing-model-version-for-training-20-vs-23) + - [Optional: Source-Free Training from Cache](#optional-source-free-training-from-cache) + - [Standard LoRA Training](#standard-lora-training) + - [DoRA LoRA Training](#dora-lora-training) + - [Advanced: LyCORIS/LoKR Training](#advanced-lycorislokr-training) + - [Training Arguments](#training-arguments) + - [Memory Optimization](#memory-optimization) + - [Quantization Options](#quantization-options) + - [Other Memory Options](#other-memory-options) + - [Aggressive VRAM Optimization (8-16GB GPUs)](#aggressive-vram-optimization-8-16gb-gpus) + - [NF4 Quantization](#nf4-quantization) + - [Model Version](#model-version) + - [Audio-Video Support](#audio-video-support) + - [Loss Function Type](#loss-function-type) + - [Loss Weighting](#loss-weighting) + - [Additional Audio Training Flags](#additional-audio-training-flags) + - [Modality Freezing (G2D)](#modality-freezing-g2d) + - [Per-Module Learning Rates](#per-module-learning-rates) + - [Per-Module LoRA Rank](#per-module-lora-rank) + - [Adaptive LoRA Rank](#adaptive-lora-rank) + - [Per-Module LoRA Dropout](#per-module-lora-dropout) + - [Preservation & Regularization](#preservation--regularization) + - [CREPA (Cross-frame Representation Alignment)](#crepa-cross-frame-representation-alignment) + - [Self-Flow (Self-Supervised Flow Matching)](#self-flow-self-supervised-flow-matching) + - [HFATO (High-Frequency Awareness Training Objective)](#hfato-high-frequency-awareness-training-objective) + - [Latent Temporal Objectives](#latent-temporal-objectives) + - [Standalone Inference Overrides](#standalone-inference-overrides) + - [Audio Quality Metrics](#audio-quality-metrics) + - [Timestep Sampling](#timestep-sampling) + - [LoRA Targets](#lora-targets) + - [LoRA Target Estimation (`ltx2_estimate.py`)](#lora-target-estimation-ltx2_estimatepy) + - [Connector LoRA (`--train_connectors`)](#connector-lora---train_connectors) + - [IC-LoRA / Video-to-Video Training](#ic-lora--video-to-video-training) + - [Audio-Reference IC-LoRA](#audio-reference-ic-lora) + - [Latent Guides](#latent-guides) + - [Sampling with Tiled VAE](#sampling-with-tiled-vae) + - [Precached Sample Prompts](#precached-sample-prompts) + - [Two-Stage Sampling](#two-stage-sampling) + - [Checkpoint Output Format](#checkpoint-output-format) + - [Resuming Training](#resuming-training) +- [Merge LoRA into Base Model](#merge-lora-into-base-model) + - [Merge-to-Base Arguments](#merge-to-base-arguments) + - [Merge-to-Base Notes](#merge-to-base-notes) +- [Merge LTX-2 LoRAs](#merge-ltx-2-loras) + - [Example Command (Windows)](#example-command-windows) + - [LoRA Merge Arguments](#lora-merge-arguments) + - [LoRA Merge Notes](#lora-merge-notes) +- [Dataset Configuration](#dataset-configuration) + - [Image Dataset Notes](#image-dataset-notes) + - [Video Dataset Options](#video-dataset-options) + - [Audio Dataset Options](#audio-dataset-options) + - [Masked Loss Datasets](#masked-loss-datasets) + - [Example TOML](#example-toml) + - [Frame Rate (FPS) Handling](#frame-rate-fps-handling) +- [Validation Datasets](#validation-datasets) + - [Configuration](#configuration) + - [Caching](#caching) + - [Training Arguments](#training-arguments-1) + - [Example](#example) + - [How It Works](#how-it-works-2) + - [Tips](#tips) +- [Directory Structure](#directory-structure) + - [Raw Dataset Layout (Example)](#raw-dataset-layout-example) + - [Cache Directory Layout (After Caching)](#cache-directory-layout-after-caching) +- [Troubleshooting](#troubleshooting) + - [Mixed Audio-Video Training](#mixed-audio-video-training) + - [Technical Notes](#technical-notes) +- [4. Slider LoRA Training](#4-slider-lora-training) + - [4a. Text-Only Mode](#4a-text-only-mode) + - [4b. Reference Mode](#4b-reference-mode) + - [4c. IC-slider](#4c-ic-slider) + - [Slider Tips](#slider-tips) +- [Windows Setup / Update Script](#windows-setup--update-script) + - [Dashboard Usage](#dashboard-usage) +- [References](#references) + +--- + +## Installation + +The base installation procedure is the same as musubi-tuner — follow the [Installation guide](../README.md#installation) (`pip install -e .` in a virtual environment). The sections below cover LTX-2-specific requirements (CUDA version, model downloads) that go on top of the base install. + +Windows users can also use [`scripts/install.ps1`](#windows-setup--update-script) as a setup/update helper. It can create or refresh the local virtual environment, install the dashboard extras, build the dashboard frontend, and write launchers for the dashboard and setup tool. + +Unless otherwise noted, command examples in this LTX-2 guide were tested on Windows 11. They should also work on Linux, but you may need small shell/path adjustments. + +For a Windows-focused community setup example for this fork (tested environment and install helpers), see [Discussion #19: Windows OS installation/usage helpers](https://github.com/AkaneTendo25/musubi-tuner/discussions/19). + +### CUDA Version + +The PyTorch install command must use a CUDA version compatible with your GPU. Adjust the `--index-url` accordingly: + +```bash +# Default (most GPUs, including RTX 30xx/40xx): +pip install torch==2.8.0 torchvision==0.23.0 torchaudio==2.8.0 --index-url https://download.pytorch.org/whl/cu126 + +# RTX 5090 / 50xx series (Blackwell): +pip install torch==2.8.0 torchvision==0.23.0 torchaudio==2.8.0 --index-url https://download.pytorch.org/whl/cu128 +``` + +Always match the CUDA version to your GPU architecture — check [PyTorch's compatibility matrix](https://pytorch.org/get-started/locally/) for the latest supported versions. + +### Downloading Required Models + +> [!WARNING] +> The dashboard UI and the Windows Setup / Update script are under active testing. Their behavior may change, and some local environments may still require manual fixes. + +You can now handle the common model downloads directly from the dashboard: + +- Use the project page to choose a template that matches your use case. +- Open `Caching`, `Training`, or `Inference` and use the download actions beside the LTX-2 and Gemma model fields. +- Use `Setup & Updates` in the dashboard to verify the install, repo state, shortcuts, and project readiness before you start caching or training. + +Manual download is still fully supported, and it remains useful if you want to manage checkpoints outside the default model directory. + +**LTX-2 Checkpoint** — use as `--ltx2_checkpoint`: +- LTX-2 (19B): [ltx-2-19b-dev.safetensors](https://huggingface.co/Lightricks/LTX-2/resolve/main/ltx-2-19b-dev.safetensors) +- LTX-2.3 (22B): [ltx-2.3-22b-dev.safetensors](https://huggingface.co/Lightricks/LTX-2.3/resolve/main/ltx-2.3-22b-dev.safetensors) + +**Gemma Text Encoder** — pick one: +- HF directory (`--gemma_root`): [gemma-3-12b-it-qat-q4_0-unquantized](https://huggingface.co/Lightricks/gemma-3-12b-it-qat-q4_0-unquantized) +- Single file (`--gemma_safetensors`): [gemma_3_12B_it_fp8_e4m3fn.safetensors](https://huggingface.co/GitMylo/LTX-2-comfy_gemma_fp8_e4m3fn/resolve/main/gemma_3_12B_it_fp8_e4m3fn.safetensors) + +Other Gemma 3 12B variants may work but not all have been tested. + +--- + +## Supported Dataset Types + +| Mode | Dataset Type | Notes | +|------|--------------|-------| +| `video` | Images | Treated as 1-frame samples (`F=1`) | +| `video` | Videos | Standard video training | +| `av` | Videos with audio | Audio extracted from video or external audio files | +| `audio` | Audio only | Dataset must be audio-only; training uses audio-driven latent geometry | + +--- + +## 1. Caching Latents + +This step pre-processes media files into VAE latents to speed up training. + +**Script:** `ltx2_cache_latents.py` + +### Latent Caching Command +```bash +python ltx2_cache_latents.py ^ + --dataset_config dataset.toml ^ + --ltx2_checkpoint /path/to/ltx-2.safetensors ^ + --device cuda ^ + --vae_dtype bf16 ^ + --ltx2_mode av ^ + --ltx2_audio_source video +``` + +### Latent Caching Arguments +- `--ltx2_mode`, `--ltx_mode`: Caching modality selector. Default is video-only (`v`/`video`). Use `av` to cache both `*_ltx2.safetensors` (video) and `*_ltx2_audio.safetensors` (audio) latents. +- `--ltx2_audio_source video|audio_files`: Use audio from the video or from external files. +- `--ltx2_audio_dir`, `--ltx2_audio_ext`: Optional when using `--ltx2_audio_source audio_files` (default extension: `.wav`). +- `--ltx2_checkpoint`: Required for `--ltx2_mode av` or `--ltx2_mode audio`. +- `--audio_only_target_resolution`: Optional square override for audio-only latent geometry. Only takes effect when `--audio_only_sequence_resolution 0`; otherwise the fixed sequence resolution is used instead. +- `--audio_only_target_fps`: Target FPS used to derive audio-only frame counts from audio duration (default: `25`). +- `--audio_video_latent_channels`: Optional override for audio-only video latent channels (auto-detected from checkpoint by default). +- `--ltx2_audio_dtype`: Data type for audio VAE encoding (default: `float16`). +- `--audio_video_latent_dtype`: Optional override for audio-only video latent dtype (defaults to `--ltx2_audio_dtype`). +- `--vae_dtype`: Data type for VAE latents (default comes from the cache script). +- `--save_dataset_manifest`: Optional. Saves a cache-only dataset manifest for source-free training. +- `--precache_sample_latents`: Cache I2V conditioning image latents for sample prompts, then continue with normal latent caching. Requires `--sample_prompts`. +- `--sample_latents_cache`: Path for the I2V conditioning latents cache file (default: `/ltx2_sample_latents_cache.pt`). +- `--reference_frames`: Number of reference frames to cache for IC-LoRA / V2V (default: `1`). +- `--reference_downscale`: Spatial downscale factor for cached reference latents (default: `1`). +- `--atomic_cache_writes`: Opt-in safety mode. Writes cache files to a temporary sibling file first, then replaces the final cache path only after a successful save. + +### Latent Cache Output Files + +| File Pattern | Contents | +|--------------|----------| +| `*_ltx2.safetensors` | Video latents: `latents_{F}x{H}x{W}_{dtype}`. If masked loss is configured, also stores `video_loss_mask`. In audio-only mode, this file also stores `ltx2_virtual_num_frames_int32` (used for timestep sampling) and `ltx2_virtual_height_int32`/`ltx2_virtual_width_int32` (only used when `--audio_only_sequence_resolution 0`). | +| `*_ltx2_audio.safetensors` | Audio latents: `audio_latents_{T}x{mel_bins}x{channels}_{dtype}`, `audio_lengths_int32`. If audio masked loss is configured, also stores `audio_loss_mask`. | + +### Memory Optimization for Caching +If you encounter Out-Of-Memory (OOM) errors during caching (especially with higher resolutions like 1080p), you have two options: + +**Option 1: VAE temporal chunking** (fewer parameters, for moderate OOM) +```bash +python ltx2_cache_latents.py ^ + ... + --vae_chunk_size 16 +``` +- `--vae_chunk_size`: Processes video in temporal chunks (e.g., 16 or 32 frames at a time). Default: `None` (all frames). + +**Option 2: VAE tiled encoding** (larger VRAM savings, for severe OOM or high-resolution videos) +```bash +python ltx2_cache_latents.py ^ + ... + --vae_spatial_tile_size 512 ^ + --vae_spatial_tile_overlap 64 +``` +- `--vae_spatial_tile_size`: Splits each frame into spatial tiles of this size in pixels (e.g., 512). Must be >= 64 and divisible by 32. Default: `None` (disabled). +- `--vae_spatial_tile_overlap`: Overlap between spatial tiles in pixels. Must be divisible by 32. Default: `64`. +- `--vae_temporal_tile_size`: Splits the video into temporal tiles of this many frames (e.g., 64). Must be >= 16 and divisible by 8. Default: `None` (disabled). +- `--vae_temporal_tile_overlap`: Overlap between temporal tiles in frames. Must be divisible by 8. Default: `24`. + +Spatial and temporal tiling can be combined. Tiled encoding trades speed for VRAM savings. + +Both options can be combined (e.g., `--vae_chunk_size 16 --vae_spatial_tile_size 512`). + +--- + +## 2. Caching Text Encoder Outputs + +This step pre-computes text embeddings using the Gemma text encoder. + +**Script:** `ltx2_cache_text_encoder_outputs.py` + +### Text Encoder Caching Command +```bash +python ltx2_cache_text_encoder_outputs.py ^ + --dataset_config dataset.toml ^ + --ltx2_checkpoint /path/to/ltx-2.safetensors ^ + --gemma_root /path/to/gemma ^ + --gemma_load_in_8bit ^ + --device cuda ^ + --mixed_precision bf16 ^ + --ltx2_mode av ^ + --batch_size 1 +``` + +### Text Encoder Caching Arguments +- `--gemma_root`: Path to the local Gemma model folder (HuggingFace format). Required unless `--gemma_safetensors` is used. +- `--gemma_safetensors`: Path to a single Gemma `.safetensors` file (e.g. an FP8 export from ComfyUI). Loads weights, config, and tokenizer from one file — no `--gemma_root` needed. See [Loading Gemma from a Single Safetensors File](#loading-gemma-from-a-single-safetensors-file) below. +- `--gemma_load_in_8bit`: Loads Gemma in 8-bit quantization. Cannot be combined with `--gemma_safetensors`. +- `--gemma_load_in_4bit`: Loads Gemma in 4-bit quantization. Cannot be combined with `--gemma_safetensors`. +- `--gemma_bnb_4bit_quant_type nf4|fp4`: Quantization type for 4-bit loading (default: `nf4`). +- `--gemma_bnb_4bit_disable_double_quant`: Disable bitsandbytes double quantization for 4-bit loading. +- `--gemma_bnb_4bit_compute_dtype auto|fp16|bf16|fp32`: Compute dtype for 4-bit operations (default: `auto`, uses `--mixed_precision` dtype). +- `--ltx2_checkpoint`: Required. Use `--ltx2_text_encoder_checkpoint` to override for text encoder connector weights. +- `--cache_before_connector`: Also save pre-connector text features (`video_features_{dtype}`, `audio_features_{dtype}`) alongside standard post-connector embeddings. Required for `--train_connectors` during training. Does not change standard cache keys; only adds extra tensors. +- `--atomic_cache_writes`: Opt-in safety mode. Writes text and prompt cache files to a temporary sibling file first, then replaces the final cache path only after a successful save. +- 8-bit/4-bit loading requires `--device cuda`. + +> [!IMPORTANT] +> `--ltx2_mode` / `--ltx_mode` **must match** the mode used during latent caching. Default is `video`; use `av` to concatenate video and audio prompt embeddings. + +### Text Encoder Output Files + +| File Pattern | Contents | +|--------------|----------| +| `*_ltx2_te.safetensors` | `video_prompt_embeds_{dtype}`, `audio_prompt_embeds_{dtype}` (av only), `prompt_attention_mask`, `text_{dtype}`, `text_mask` | +| (with `--cache_before_connector`) | Above keys plus `video_features_{dtype}`, `audio_features_{dtype}` (av only) | + +### Loading Gemma from a Single Safetensors File + +`--gemma_safetensors` loads Gemma from a single `.safetensors` file instead of a HuggingFace model directory. Weights, tokenizer (`spiece_model` key), and config (inferred from tensor shapes) are all read from the one file. No `--gemma_root` needed. + +```bash +python ltx2_cache_text_encoder_outputs.py ^ + --dataset_config dataset.toml ^ + --ltx2_checkpoint /path/to/ltx-2.safetensors ^ + --gemma_safetensors /path/to/gemma3-12b-it-fp8.safetensors ^ + --device cuda ^ + --mixed_precision bf16 +``` + +- FP8 weights (`F8_E4M3` / `F8_E5M2`) are detected automatically and kept in FP8 on GPU (compute in bf16). +- `--gemma_fp8_weight_offload` / `--no-gemma_fp8_weight_offload`: Explicitly enable or disable CPU offload for FP8 Gemma linear weights when using `--gemma_safetensors`. +- If `--gemma_fp8_weight_offload` is omitted, the code falls back to `LTX2_GEMMA_SAFETENSORS_WEIGHT_OFFLOAD` (default environment fallback: enabled / `1`). +- `--gemma_load_in_8bit` / `--gemma_load_in_4bit` cannot be combined with `--gemma_safetensors`. +- If the file has no `spiece_model` key, tokenizer extraction fails — use `--gemma_root` instead. +- Works in all scripts that load Gemma: `ltx2_cache_text_encoder_outputs.py`, `ltx2_train_network.py`, `ltx2_train_slider.py`, `ltx2_generate_video.py`. + +--- + +## 3. Training + +Launch the training loop using `accelerate`. + +**Script:** `ltx2_train_network.py` + +### Choosing Model Version for Training (2.0 vs 2.3) + +Use this rule: + +| Checkpoint you train on | Required training flags | +|---|---| +| LTX-2 (19B) checkpoint | `--ltx_version 2.0` | +| LTX-2.3 (22B) checkpoint | `--ltx_version 2.3` | + +Recommended practice: +- Always set `--ltx_version` explicitly in training commands (do not rely on the default). +- On first run, set `--ltx_version_check_mode error` to fail fast if the selected version does not match checkpoint metadata. +- After validation, you can switch to `--ltx_version_check_mode warn`. +- Pre-quantized FP8 checkpoints (e.g. `ltx-2.3-22b-dev-fp8.safetensors`) are supported. The loader auto-detects `weight_scale`/`input_scale` keys and dequantizes to bf16 before applying LoRA merges and any further quantization. + +When changing checkpoints (important): +- If you change `--ltx2_checkpoint` (e.g., LTX-2 -> LTX-2.3, or different 2.3 variant), re-run **both** caches: + - `ltx2_cache_latents.py` + - `ltx2_cache_text_encoder_outputs.py` +- Do not reuse old `*_ltx2_te.safetensors` from a different checkpoint. For LTX-2.3 audio/av training this can cause context/mask shape mismatches (for example FlashAttention varlen mask-length errors). +- If you use `--dataset_manifest`, regenerate it from the recache step so training points to the new cache files. +- Pre-quantized FP8 checkpoints (`*fp8*.safetensors`) work with both `--fp8_base` and `--fp8_base --fp8_scaled`. The loader dequantizes to bf16 using the checkpoint's scale tensors before any further processing. + +Example (LTX-2.3 training): +```bash +--ltx2_checkpoint /path/to/ltx-2.3.safetensors ^ +--ltx_version 2.3 ^ +--ltx_version_check_mode error +``` + +### Optional: Source-Free Training from Cache +If you cached with `--save_dataset_manifest`, you can train without source dataset paths: + +```bash +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 ltx2_train_network.py ^ + --dataset_manifest dataset_manifest.json ^ + ... (other training args) +``` + +Use `--dataset_manifest` instead of `--dataset_config`. + +Dashboard workflow: the Project page has a **Cache & Start Training** action. It runs latent caching, waits for success, runs text caching, waits for success, and then starts training. The Project page shows the active stage, shared progress, a stop button for the running stage, and links to open the relevant caching or training view. If no dataset manifest path is set, the action uses `dataset_manifest.json` in the project folder and sets both caching and training to that manifest before it starts. + +### Standard LoRA Training +```bash +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 ltx2_train_network.py ^ + --mixed_precision bf16 ^ + --dataset_config dataset.toml ^ + --gemma_load_in_8bit ^ + --gemma_root /path/to/gemma ^ + --separate_audio_buckets ^ + --ltx2_checkpoint /path/to/ltx-2.3.safetensors ^ + --ltx_version 2.3 ^ + --ltx_version_check_mode error ^ + --ltx2_mode av ^ + --fp8_base ^ + --fp8_scaled ^ + --blocks_to_swap 10 ^ + --sdpa ^ + --gradient_checkpointing ^ + --learning_rate 1e-4 ^ + --network_module networks.lora_ltx2 ^ + --network_dim 32 ^ + --network_alpha 32 ^ + --timestep_sampling shifted_logit_normal ^ + --sample_at_first ^ + --sample_every_n_epochs 5 ^ + --sample_prompts sampling_prompts.txt ^ + --sample_with_offloading ^ + --sample_tiled_vae ^ + --sample_vae_tile_size 512 ^ + --sample_vae_tile_overlap 64 ^ + --sample_vae_temporal_tile_size 48 ^ + --sample_vae_temporal_tile_overlap 8 ^ + --sample_merge_audio ^ + --output_dir output ^ + --output_name ltx23_lora +``` + +Pre-quantized FP8 checkpoints (`*fp8*.safetensors`) are supported — `--fp8_base --fp8_scaled` works the same as with standard checkpoints (weights are dequantized to bf16 first, then re-quantized). + +For LTX-2 checkpoints, replace: +- `--ltx2_checkpoint /path/to/ltx-2.3.safetensors` -> `--ltx2_checkpoint /path/to/ltx-2.safetensors` +- `--ltx_version 2.3` -> `--ltx_version 2.0` + +### DoRA LoRA Training + +DoRA adds a separate learnable magnitude vector to the standard LTX-2 LoRA backend. It is opt-in and uses the same target presets, rank, alpha, optimizer, and dataset settings as regular LoRA. + +```bash +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 ltx2_train_network.py ^ + ... (same args as standard LoRA) ^ + --network_module networks.lora_ltx2 ^ + --network_dim 32 ^ + --network_alpha 16 ^ + --network_args "use_dora=true" ^ + --output_name ltx2_dora +``` + +In the dashboard, enable the **DoRA** toggle in the LoRA section. When disabled, the generated command does not include `use_dora=true`. + +Training-time ComfyUI export is supported for DoRA LoRA. The native Musubi checkpoint stores `lora_magnitude_vector.weight`; the generated `*.comfy.safetensors` file stores the equivalent ComfyUI `dora_scale` tensors. + +The same `use_dora=true` flag enables DokR when the native LoKr backend is selected: + +```bash +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 ltx2_train_network.py ^ + ... (same args as standard LoRA) ^ + --network_module networks.lokr ^ + --network_dim 16 ^ + --network_alpha 16 ^ + --network_args "use_dora=true" ^ + --output_name ltx2_dokr +``` + +DokR is also opt-in. Without `use_dora=true`, `networks.lokr` keeps the regular LoKr path. + +### Advanced: LyCORIS/LoKR Training + +musubi-tuner supports advanced LoRA algorithms (LoKR, LoHA, LoCoN, etc.) via: +- `--network_args` for inline `key=value` settings +- `--lycoris_config ` for TOML-based settings + +See the [LyCORIS algorithm list](https://github.com/KohakuBlueleaf/LyCORIS/blob/main/docs/Algo-List.md) and [guidelines](https://github.com/KohakuBlueleaf/LyCORIS/blob/main/docs/Guidelines.md) for algorithm details and recommended settings. You can also refer to the local [LoHa/LoKr documentation](./loha_lokr.md). + +No bundled example TOML files are shipped; provide your own config path. + +```bash +# Install LyCORIS first +pip install lycoris-lora + +# Example TOML (save anywhere, e.g. my_lycoris.toml) +# [network] +# base_algo = "lokr" +# base_factor = 16 +# +# [network.modules."*audio*"] +# algo = "lora" +# dim = 64 +# alpha = 32 +# +# [network.init] +# lokr_norm = 1e-3 + +# LoKR example +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 ltx2_train_network.py ^ + ... (same args as above) ^ + --lora_target_preset lycoris ^ + --network_module lycoris.kohya ^ + --lycoris_config my_lycoris.toml ^ + --output_name ltx2_lokr + +# LoCoN example (inline args) +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 ltx2_train_network.py ^ + ... (same args as above) ^ + --network_module lycoris.kohya ^ + --network_args "algo=locon" "conv_dim=8" "conv_alpha=4" ^ + --output_name ltx2_locon +``` + +**Target format (`--network_args`)** +- Pass args as space-separated `key=value` pairs. +- Each pair is one argument token: `--network_args "key1=value1" "key2=value2"`. +- Common LyCORIS keys: `algo`, `factor`, `conv_dim`, `conv_alpha`, `dropout`. +- Use `--init_lokr_norm` only with LoKR (`algo=lokr`). +- If both TOML and `--network_args` are used, `--network_args` can override nested TOML keys with: + - `modules..=...` + - `init.=...` + +`--lycoris_config` requires `--network_module lycoris.kohya`. + +### Training Arguments + +All training arguments can be placed in a `.toml` config file instead of on the command line via `--config_file config.toml`. See the [configuration files guide](./advanced_config.md) for format details. + +#### Memory Optimization + +For additional training and inference speedups, see the [torch.compile Support](./torch_compile.md) documentation. + +##### Quantization Options + +| Method | VRAM (19B, LTX-2) | Weight Error (MAE) | SNR | Cosine Similarity | +|--------|------------------|--------------------|-----|-------------------| +| BF16 (baseline) | ~38 GB | 0.0011 | 55.6 dB | 0.999999 | +| `--fp8_base --fp8_scaled` | ~19 GB | 0.0171 (15x BF16) | 32.0 dB | 0.999686 | +| `--nf4_base` | ~10 GB | 0.0678 (60x BF16) | 21.2 dB | 0.996188 | +| `--nf4_base --loftq_init` | ~10 GB | 0.0654 (60x BF16) | 21.5 dB | 0.996437 | + +*Approximate values measured on random N(0,1) weights with shapes representative of LTX-2 transformer layers. MAE = mean absolute error between original and dequantized weights. LoftQ error is measured after adding the LoRA correction (rank 32, 2 iterations). No benchmark script is included in this repo.* + +NF4 has ~4x higher weight error than FP8 (cosine 0.996 vs 0.9997). The base model is frozen during LoRA training, so the quantization error is constant rather than accumulating. LoftQ initializes LoRA weights from the quantization residual via SVD. + +- `--fp8_base`: keep base model weights in FP8 path (~19 GB VRAM). +- `--fp8_scaled`: quantize checkpoint weights to FP8 at load time. Works with both standard (bf16/fp16/fp32) and pre-quantized FP8 checkpoints (the latter are dequantized to bf16 first, then re-quantized). +- `--fp8_keep_blocks "0,1,2,45"`: with `--fp8_scaled`, keep selected transformer blocks in high precision instead of FP8. Comma lists and ranges such as `0-2,45` are accepted. This is useful for testing whether boundary or otherwise sensitive blocks should avoid FP8 quantization. +- `--fp8_w8a8`: with `--fp8_base --fp8_scaled`, use W8A8 activation quantization for LoRA training. `--w8a8_mode int8` is the default; `--w8a8_mode fp8` keeps FP8 weights and dequantizes transiently. +- `--nf4_base`: NF4 4-bit quantization (~10 GB VRAM). Mutually exclusive with `--fp8_base`. See [NF4 Quantization](#nf4-quantization) below. +- `--quantize_device cpu|cuda|gpu`: Device for NF4/FP8 quantization at startup (default: `cuda`). `cpu` loads and quantizes weights on CPU, then moves to GPU. `cuda` loads and quantizes directly on GPU. Overrides `LTX2_NF4_CALC_DEVICE` / `LTX2_FP8_CALC_DEVICE` env vars. + +##### Other Memory Options + +| Argument | Description | +|----------|-------------| +| `--blocks_to_swap X` | Offload X transformer blocks to CPU (max 47 for 48-block model). Higher = more VRAM saved, more CPU↔GPU overhead | +| `--use_pinned_memory_for_block_swap` | Use pinned memory for faster CPU↔GPU block transfers | +| `--gradient_checkpointing` | Reduce VRAM by recomputing activations during backward pass | +| `--gradient_checkpointing_cpu_offload` | Offload activations to CPU during gradient checkpointing | +| `--offload_optimizer_during_validation` | Offload CUDA optimizer state to CPU during validation and sample previews (off by default) | +| `--ffn_chunk_target` | `all`, `video`, or `audio` — enable FFN chunking for selected modules | +| `--ffn_chunk_size N` | Chunk size for FFN chunking (0 = disabled) | +| `--split_attn_target` | `none`, `all`, `self`, `cross`, `text_cross`, `av_cross`, `video`, `audio` — split attention target modules | +| `--split_attn_mode` | `batch` or `query` — split by batch dimension or query length | +| `--split_attn_chunk_size N` | Chunk size for query-based split attention (0 = default 1024) | +| `--ddp_find_unused_parameters` | Enable DDP unused-parameter detection for branchy LoRA targets (off by default) | +| `--gemma_bnb_use_local_rank` | For Gemma 8-bit/4-bit loading, pin the quantized model to this process's `LOCAL_RANK` GPU (off by default) | +| `--sdpa` | Use PyTorch scaled dot-product attention (recommended default) | +| `--flash_attn` | Use FlashAttention 2 (requires `flash-attn` package built for your CUDA + PyTorch) | +| `--flash3` | Use FlashAttention 3 (requires `flash-attn` v3 with Hopper+ GPU) | + +#### Aggressive VRAM Optimization (8-16GB GPUs) + +For maximum VRAM savings on 8-16GB GPUs, use this combination of flags. See also the [Advanced Configuration guide](./advanced_config.md) for optimizer options (`--optimizer_type`, `--lr_scheduler`, Schedule-Free optimizer, etc.): + +```bash +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 ltx2_train_network.py ^ + --mixed_precision bf16 ^ + --dataset_config dataset.toml ^ + --ltx2_checkpoint /path/to/ltx-2.safetensors ^ + --ltx2_mode av ^ + --gemma_load_in_8bit ^ + --gemma_root /path/to/gemma ^ + --fp8_base ^ + --fp8_scaled ^ + --blocks_to_swap 47 ^ + --use_pinned_memory_for_block_swap ^ + --gradient_checkpointing ^ + --gradient_checkpointing_cpu_offload ^ + --sdpa ^ + --network_module networks.lora_ltx2 ^ + --network_dim 16 ^ + --network_alpha 16 ^ + --sample_with_offloading ^ + --sample_tiled_vae ^ + --sample_vae_tile_size 512 ^ + --sample_vae_temporal_tile_size 48 ^ + --output_dir output +``` + +**Tips for low-VRAM training:** +- Use `--fp8_base --fp8_scaled` (works with both standard and pre-quantized FP8 checkpoints) +- Use `--blocks_to_swap 47` (keeps only 1 block on GPU) +- Use smaller LoRA rank (`--network_dim 16` instead of 32) +- Use smaller training resolutions (e.g., 512x320) +- Reduce `--sample_vae_temporal_tile_size` to 24 or lower +- Use `--use_pinned_memory_for_block_swap` - faster transfers + +#### NF4 Quantization + +NF4 (4-bit NormalFloat) quantization uses a 16-value codebook optimized for normally-distributed weights (QLoRA paper). Weights are stored as packed uint8 with per-block absmax scaling. VRAM usage is ~10 GB vs ~19 GB for FP8 and ~38 GB for BF16. + +**Basic usage:** +```bash +accelerate launch ... ltx2_train_network.py ^ + --nf4_base ^ + --network_module networks.lora_ltx2 ^ + --network_dim 32 ^ + ... +``` + +**With LoftQ initialization:** + +LoftQ pre-computes LoRA A/B matrices from the truncated SVD of the NF4 quantization residual (`W - dequant(Q(W))`). This runs once at startup and adds no runtime cost. + +```bash +accelerate launch ... ltx2_train_network.py ^ + --nf4_base ^ + --loftq_init ^ + --loftq_iters 2 ^ + --network_module networks.lora_ltx2 ^ + --network_dim 32 ^ + ... +``` + +| Argument | Default | Description | +|----------|---------|-------------| +| `--nf4_base` | off | Enable NF4 4-bit quantization for the base model | +| `--nf4_block_size` | 32 | Elements per quantization block | +| `--loftq_init` | off | LoftQ initialization for LoRA (requires `--nf4_base`) | +| `--loftq_iters` | 2 | Number of alternating quantize-SVD iterations | +| `--awq_calibration` | off | Experimental: activation-aware channel scaling before quantization | +| `--awq_alpha` | 0.25 | AWQ scaling strength (0 = no effect, 1 = full) | +| `--awq_num_batches` | 8 | Number of synthetic calibration batches for AWQ | +| `--quantize_device` | `cuda` | Device for quantization math (`cpu`, `cuda`, `gpu`) | + +**Pre-quantized models (recommended):** + +By default, NF4 quantization runs from scratch on every startup. `ltx2_quantize_model.py` quantizes once and saves the result (~42% of the original file size). The training/inference code auto-detects pre-quantized checkpoints via safetensors metadata and skips re-quantization. + +```bash +python src/musubi_tuner/ltx2_quantize_model.py ^ + --input_model path/to/ltx-2.3-22b-dev.safetensors ^ + --output_model path/to/ltx-2.3-22b-dev-nf4.safetensors ^ + --loftq_init --network_dim 32 +``` + +Output files (kept in the same directory): +- `*-nf4.safetensors` — quantized model (transformer in NF4, VAE and other components unchanged) +- `*-nf4.loftq_r32.safetensors` — pre-computed LoftQ init for rank 32 (only with `--loftq_init`) + +Then use it exactly like the original checkpoint — just point `--ltx2_checkpoint` at the NF4 file. `--nf4_base` is still required (enables the runtime dequantization patch): + +```bash +accelerate launch ... ltx2_train_network.py ^ + --ltx2_checkpoint path/to/ltx-2.3-22b-dev-nf4.safetensors ^ + --nf4_base --loftq_init --network_dim 32 ^ + ... +``` + +| Argument | Default | Description | +|----------|---------|-------------| +| `--input_model` | required | Path to original `.safetensors` checkpoint | +| `--output_model` | required | Path for quantized output | +| `--nf4_block_size` | 32 | Elements per quantization block | +| `--calc_device` | `cuda` if available | Device for quantization computation | +| `--loftq_init` | off | Pre-compute LoftQ initialization (requires `--network_dim`) | +| `--loftq_iters` | 2 | Number of LoftQ alternating iterations | +| `--network_dim` | 0 | LoRA rank for LoftQ (must match training `--network_dim`) | + +- LoftQ is rank-specific: changing `--network_dim` requires re-running the quantize script with the new rank. The quantized model itself does not need to be regenerated. +- `--awq_calibration` is incompatible with pre-quantized models (requires full-precision weights). +- Pre-quantized checkpoints use the same NF4 packing/dequantization path as runtime dynamic quantization for the same block size. Exact byte equality can still depend on device, PyTorch, and CUDA behavior. + +**Notes:** +- `--nf4_base` and `--fp8_base` are mutually exclusive. +- `--loftq_init` requires `--nf4_base`. +- `--awq_calibration` is experimental. Adds a per-layer division during forward passes. In synthetic tests, reduces activation-weighted error by ~3-5%; effect on real training quality has not been validated. +- Compatible with `--blocks_to_swap`, `--gradient_checkpointing`, and other training options. NF4 reduces block swap transfer size (4-bit vs 16-bit per weight). +- Quantization targets transformer block weights only. Embedding layers, norms, and projection layers remain in full precision. + +#### Model Version +- `--ltx_version 2.0|2.3`: Select target model version (default: `2.3`). Controls default behavior for version-dependent settings (e.g., `--shifted_logit_mode` defaults to `legacy` for 2.0, `stretched` for 2.3). +- `--ltx_version_check_mode off|warn|error`: How to handle mismatch between `--ltx_version` and checkpoint metadata (default: `warn`). The trainer reads checkpoint config keys (`cross_attention_adaln`, `caption_proj_before_connector`, `bwe` vocoder) to detect the actual version. + +#### Audio-Video Support +- `--ltx2_mode`, `--ltx_mode`: Training modality selector. Default is `v` (`video`). Values: `video`, `av`, `audio` (aliases: `v`, `va`, `a`). +- `--ltx2_audio_only_model`: Force loading a physically audio-only transformer variant (video modules omitted). Requires `--ltx2_mode audio`. +- `--separate_audio_buckets`: Keeps audio and non-audio items in separate batches (reduces VRAM for image/video-only batches). +- `--audio_bucket_strategy pad|truncate`: Audio duration bucketing strategy. `pad` (default) rounds to nearest bucket boundary and pads shorter clips with loss masking. `truncate` floors to bucket boundary and truncates all clips to bucket length (no padding or masking needed). +- `--audio_bucket_interval`: Audio bucket step size in seconds (default: `2.0`). Controls how finely audio clips are grouped by duration. +- `--min_audio_batches_per_accum`: Minimum number of audio-bearing microbatches per gradient accumulation window. +- `--audio_batch_probability`: Probability of selecting an audio-bearing batch when both audio and non-audio batches are available. + - `--min_audio_batches_per_accum` and `--audio_batch_probability` are mutually exclusive. + - In LTX-2 training these flags enable an audio-aware DataLoader sampler. They cannot be combined with `--accumulation_group_by`, because PyTorch only accepts one sampler for the DataLoader. + - They can be combined with `--audio_loss_balance_mode`, per-modality caption dropout, `--audio_supervision_mode`, `--dcr`, and `--tarp`. + - For a first mixed AV trial, `--audio_batch_probability 0.4` is a reasonable starting point. With gradient accumulation, use `--min_audio_batches_per_accum 1` instead. +- `--accumulation_group_by none|frames|bucket|dataset`: Opt-in ordering for gradient accumulation windows. `bucket` keeps each virtual batch on one full dataset bucket key (resolution/frame/audio), which is useful for mixed frame-length datasets with `--gradient_accumulation_steps > 1`. +- `--accumulation_group_remainder drop|pad|allow_mixed`: Handles buckets that do not divide evenly by the accumulation window. `drop` skips incomplete windows, `pad` repeats same-group batches, and `allow_mixed` keeps all batches but may mix groups in final windows. +- `caption_extension`: For directory datasets, use a different caption file suffix to select alternate captions. For example, `caption_extension = ".target.txt"` reads `clip.target.txt` for `clip.mp4`/`clip.png`. This is the directory-dataset equivalent of JSONL caption routing. +- `--caption_field`: For JSONL datasets, use this metadata field instead of `caption` when caching/training text embeddings. For I2V/reference datasets, store fields such as `target_caption` and `reference_caption`, then cache with `--caption_field target_caption` when the text conditioning should describe the target video/motion. +- `--caption_dropout_rate`: Probability of dropping ALL text conditioning (video + audio) for a sample during training (default: `0.0`, disabled). When triggered, the sample's text embeddings are zeroed and the attention mask is disabled except for one placeholder token kept active for shape/runtime safety. This trains the model to generate without text guidance and enables classifier-free guidance (CFG) at inference. +- `--video_caption_dropout_rate`: Probability of dropping only the video text conditioning while keeping audio text conditioning (default: `0.0`). AV mode only. Applied independently per sample before `--caption_dropout_rate`. +- `--audio_caption_dropout_rate`: Probability of dropping only the audio text conditioning while keeping video text conditioning (default: `0.0`). AV mode only. Applied independently per sample before `--caption_dropout_rate`. + +The three dropout rates are independent. For a given sample, the per-modality dropout is applied first (on the separate `video_prompt_embeds` / `audio_prompt_embeds`), then the joint dropout is applied on the concatenated result. A sample can end up with: both modalities present, video-only, audio-only, or fully unconditional. + +For balanced AV or `av_ic` runs, per-modality dropout can be combined with the audio-aware sampler, `--audio_loss_balance_mode ema_mag`, and `--dcr`. A modest first pass is `--video_caption_dropout_rate 0.05 --audio_caption_dropout_rate 0.10`. + +#### Loss Function Type + +`--loss_type` selects the element-wise loss function used for both video and audio branches. Default is `mse`. + +| `--loss_type` | PyTorch function | Per-element formula | +|---|---|---| +| `mse` (default) | `F.mse_loss` | `(pred - tgt)²` | +| `mae` / `l1` | `F.l1_loss` | `\|pred - tgt\|` | +| `huber` / `smooth_l1` | `F.smooth_l1_loss` | `0.5·(pred-tgt)²/δ` when `\|pred-tgt\| < δ`, else `\|pred-tgt\| - 0.5·δ` | + +- `--huber_delta` (float, default: 1.0): Transition point for Huber loss. Only used when `--loss_type` is `huber` or `smooth_l1`. Smaller values make the loss behave more like L1; larger values more like MSE. + +All other training mechanics (weighting scheme, masking, audio balancing) apply on top of the chosen loss unchanged. + +```bash +# L1 loss +--loss_type mae + +# Huber with tighter quadratic region +--loss_type huber --huber_delta 0.1 +``` + +#### Loss Weighting +- `--video_loss_weight`: Weight for video loss (default: 1.0). +- `--audio_loss_weight`: Weight for audio loss in AV mode (default: 1.0). +- Dataset config `video_loss_weight` / `audio_loss_weight` override the corresponding CLI weight for that dataset only. +- `--audio_loss_balance_mode`: Audio loss balancing strategy. Values: `none` (default), `inv_freq`, `ema_mag`, `uncertainty`, `ogm_ge`. +- `--audio_loss_balance_min`, `--audio_loss_balance_max`: Clamp range for effective audio weight (defaults: 0.05, 4.0). Used by `inv_freq` and `ema_mag` only. + +**`inv_freq` mode** — inverse-frequency reweighting for mixed audio/non-audio training. Boosts audio loss proportionally to how rare audio batches are. + +- `--audio_loss_balance_beta`: EMA update rate for observed audio-batch frequency (default: 0.01). +- `--audio_loss_balance_eps`: Denominator floor for inverse-frequency scaling (default: 0.05). +- `--audio_loss_balance_ema_init`: Initial audio-frequency EMA value (default: 1.0). + +Example: +```bash +--audio_loss_weight 1.0 ^ +--audio_loss_balance_mode inv_freq ^ +--audio_loss_balance_beta 0.01 ^ +--audio_loss_balance_eps 0.05 ^ +--audio_loss_balance_min 0.05 ^ +--audio_loss_balance_max 3.0 +``` + +Recommended start values: +- `--audio_loss_balance_beta 0.01` (stable EMA, slower reaction; try `0.02-0.05` for faster reaction) +- `--audio_loss_balance_eps 0.05` (safe floor; increase to `0.1` if weights spike too much) +- `--audio_loss_balance_min 0.05 --audio_loss_balance_max 3.0` (conservative clamp range) +- `--audio_loss_balance_ema_init 1.0` (no warm-start boost; use `0.5` only if you want stronger early audio emphasis) + +For audio-starved mixed datasets, `inv_freq` can be combined with `--audio_batch_probability` or `--min_audio_batches_per_accum`, plus `--audio_supervision_mode warn --audio_supervision_min_ratio 0.5`. + +**`ema_mag` mode** — dynamic balancing by matching audio-loss EMA magnitude to a target fraction of video-loss EMA. Bidirectional: can dampen audio (weight < 1.0) when audio loss exceeds `target_ratio * video_loss`, or boost it when audio loss is below that target. + +- `--audio_loss_balance_target_ratio`: Target audio/video loss magnitude ratio (default: 0.33 — audio loss targets ~33% of video loss). +- `--audio_loss_balance_ema_decay`: EMA decay for loss magnitude tracking (default: 0.99). + +Example: +```bash +--audio_loss_weight 1.0 ^ +--audio_loss_balance_mode ema_mag ^ +--audio_loss_balance_target_ratio 0.33 ^ +--audio_loss_balance_ema_decay 0.99 ^ +--audio_loss_balance_min 0.05 ^ +--audio_loss_balance_max 4.0 +``` + +Use `ema_mag` when audio and video losses have different natural magnitudes and you want automatic scaling instead of manual `--audio_loss_weight` tuning. + +For balanced AV or `av_ic` runs, `--audio_loss_balance_target_ratio 0.33` can be combined with the audio-aware sampler, per-modality caption dropout, and `--dcr`. If audio improves while video or identity quality drifts, try a lower target such as `0.25` together with lower `--audio_lr`, lower `--audio_dim`, or modality freezing. + +**`uncertainty` mode** — learnable homoscedastic uncertainty weighting ([Kendall et al., CVPR 2018](https://arxiv.org/abs/1705.07115)). Two log-variance scalars (`log_var_video`, `log_var_audio`) are added to the optimizer and learned jointly with LoRA weights. The combined loss is: + +``` +loss = 0.5 * exp(-log_var_v) * L_video + 0.5 * log_var_v + + 0.5 * exp(-log_var_a) * L_audio + 0.5 * log_var_a +``` + +The regularization terms (`0.5 * log_var`) penalize large variance, preventing either loss from being scaled to zero. Both scalars are initialized to 0.0 and optimized via backpropagation. `--video_loss_weight` and `--audio_loss_weight` are ignored in this mode. + +- `--uncertainty_lr`: Learning rate for log-variance parameters (default: same as `--learning_rate`). + +Example: +```bash +--audio_loss_balance_mode uncertainty +``` + +Logged to TensorBoard: `uncertainty/log_var_video`, `uncertainty/log_var_audio`, `uncertainty/precision_video`, `uncertainty/precision_audio`. Higher precision = more weight on that modality's loss. The log-variance params are saved/loaded with checkpoints for training resume. + +**`ogm_ge` mode** — Online Gradient Modulation with optional Generalization Enhancement noise. The lower-loss / faster-learning modality is attenuated on each AV step using a discrepancy-dependent coefficient: + +``` +k = 1 - tanh(alpha * discrepancy) +``` + +The weaker modality keeps coefficient `1.0`. This is an opt-in conservative implementation for joint AV LoRA training: + +- `--ogm_ge_alpha`: Modulation strength (default: `0.3`) +- `--ogm_ge_noise_std`: Optional GE noise scale added to the attenuated modality gradients after backward (default: `0.0`, disabled) + +Example: +```bash +--audio_loss_balance_mode ogm_ge ^ +--ogm_ge_alpha 0.3 ^ +--ogm_ge_noise_std 0.0 +``` + +Logged to TensorBoard: `ogm_ge/video_coeff`, `ogm_ge/audio_coeff`, `ogm_ge/discrepancy`. + +On video-only batches (no audio in the current batch), falls back to standard `video_loss * video_weight`. + +#### Additional Audio Training Flags + +- `--independent_audio_timestep`: Sample a separate timestep for audio (AV/audio modes only). +- `--audio_silence_regularizer`: When AV batches are missing audio latents, use synthetic silence latents instead of skipping the audio branch. +- `--audio_silence_regularizer_weight`: Loss multiplier for synthetic-silence fallback batches. +- `--audio_supervision_mode off|warn|error`: AV audio-supervision monitor mode. +- `--audio_supervision_warmup_steps`: Expected AV batches before supervision checks. +- `--audio_supervision_check_interval`: Run supervision checks every N expected AV batches. +- `--audio_supervision_min_ratio`: Minimum supervised/expected ratio required by the monitor. + +For mixed datasets where `loss_a` is absent for long stretches, the supervision monitor can be combined with the audio-aware sampler and `--audio_loss_balance_mode inv_freq`. Use `warn` first to confirm the ratio before switching to `error`. + +#### Modality Freezing (G2D) + +Adaptive modality freezing based on per-modality loss EMA ratio, inspired by G2D Sequential Modality Prioritization ([arXiv 2506.21514](https://arxiv.org/abs/2506.21514)). When one modality's loss is significantly lower than the other, its LoRA parameters are frozen (`requires_grad=False`) so the under-performing modality can train without gradient interference. + +- `--modality_freeze_check_interval `: Check freeze state every N steps. `0` = disabled (default). +- `--modality_freeze_ratio_threshold `: Freeze threshold (default: `0.5`). Audio LoRA is frozen when `audio_loss_ema / video_loss_ema < threshold`. Video LoRA is frozen when the ratio exceeds `1 / threshold`. +- `--modality_freeze_warmup_steps `: Steps before freezing can activate (default: `100`). +- `--modality_freeze_ema_decay `: EMA decay for loss tracking (default: `0.99`). + +Example: +```bash +--modality_freeze_check_interval 500 ^ +--modality_freeze_ratio_threshold 0.5 ^ +--modality_freeze_warmup_steps 200 +``` + +Logged to TensorBoard: `modality_freeze/state` (0=both active, 1=audio frozen, -1=video frozen), `modality_freeze/video_loss_ema`, `modality_freeze/audio_loss_ema`. + +For audio-overfitting cases, modality freezing can be combined with `--audio_loss_balance_mode ema_mag`, a lower `--audio_lr`, and lower audio LoRA rank. + +#### Optimizers + +LTX-2 training accepts optimizer selection through `--optimizer_type`; optimizer arguments are passed with `--optimizer_args "key=value" ...`. Optional package rows require that package to be installed in the active Python environment. + +| Optimizer | Use when | Extra package | Fused backward | Notes | +| --- | --- | --- | --- | --- | +| `AdamW` | You want the standard PyTorch optimizer path. | No | No | Pass regular AdamW constructor options through `--optimizer_args`. | +| `AdamW8bit`, `PagedAdamW8bit`, `PagedAdam8bit` | You want bitsandbytes optimizer-state memory savings. | `bitsandbytes` | No | The paged variants require a bitsandbytes build that provides those classes. | +| `Adafactor` | You want Adafactor's factored optimizer state and scheduler behavior. | No | Yes | If `relative_step` is omitted, it defaults to `True`; relative-step mode uses the Adafactor scheduler path. | +| `CAME`, `CAMESimple`, `came_simple` | You want CAME without 8-bit optimizer-state quantization. | No | Yes | Supports `stochastic_rounding`, `use_cautious`, and related CAME args through `--optimizer_args`. | +| `CAME8bit`, `came_8bit` | You want CAME with block-wise 8-bit optimizer state for eligible tensors. | No | Yes | Supports the same CAME args plus 8-bit state settings such as `min_8bit_size` and `quant_block_size`. | +| `SinkSGD`, `SinkSGD_adv`, `sinksgd`, `sink_sgd`, `sinksgdadv` | You want Sinkhorn-normalized SGD with momentum for LoRA-style training. | No | Yes | Supports `momentum`, `nesterov`, `nesterov_coef`, `normed_momentum`, `weight_decay`, `sinkhorn_iterations`, `orthogonal_sinkhorn`, `orthogonal_gradient`, `spectral_normalization`, and `state_precision`. State precision modes are `auto`, `fp32`, and `bf16_sr`. Optional LR scaling requires explicit args such as `scale_lr_with_grad_accum=True` or `scale_lr_with_effective_batch=True`. | + +#### Per-Module Learning Rates + +Set different learning rates for audio vs. video LoRA modules. Useful when audio modules need a lower LR to stabilize AV training. + +- `--audio_lr `: Learning rate for all audio LoRA modules (names containing `audio_`). Defaults to `--learning_rate`. +- `--lr_args ...`: Regex-based per-module LR overrides. Patterns are matched against LoRA module names via `re.search`. + +Priority (highest to lowest): `--lr_args` pattern match > `--audio_lr` catch-all > `--learning_rate` default. + +Example: +```bash +--learning_rate 1e-4 ^ +--audio_lr 1e-5 ^ +--lr_args audio_attn=1e-6 video_to_audio=5e-6 +``` + +Result: +- `audio_attn` modules → 1e-6 (matched by `--lr_args`) +- `video_to_audio` modules → 5e-6 (matched by `--lr_args`) +- Other `audio_*` modules (e.g. `audio_ff`) → 1e-5 (`--audio_lr`) +- Video modules → 1e-4 (`--learning_rate`) + +Works with LoRA+ (`loraplus_lr_ratio`): the up/down split applies within each LR group. Both flags default to `None` and are fully backward-compatible. See [LoRA+ in the advanced configuration guide](./advanced_config.md#lora) for setup details. + +Optional per-group warmup overrides: + +- `--lr_group_warmup_args ...`: Override warmup length for matching optimizer groups while keeping the selected scheduler family and default path unchanged. Patterns match group names such as `unet_audio`, `unet_video`, or regex-derived names from `--lr_args`. + +Example: +```bash +--learning_rate 1e-4 ^ +--audio_lr 3e-5 ^ +--lr_scheduler cosine ^ +--lr_warmup_steps 500 ^ +--lr_group_warmup_args audio=500 video=1500 +``` + +This keeps audio groups on a shorter warmup and video groups on a longer warmup without changing existing behavior unless `--lr_group_warmup_args` is provided. + +When audio learns faster than video, a lower `--audio_lr` such as `3e-5` with a `1e-4` base LR can be combined with `--audio_loss_balance_mode ema_mag` and lower audio LoRA rank. + +#### Per-Module LoRA Rank + +Set different LoRA rank (dim) for audio vs. video modules. + +- `--audio_dim `: LoRA rank for audio modules (names containing `audio_`). Defaults to `--network_dim`. +- `--audio_alpha `: LoRA alpha for audio modules. Defaults to `--network_alpha`. +- `--network_args "cross_modal_dim="`: Optional LoRA rank override for cross-modal modules (`audio_to_video`, `video_to_audio`, `av_ca_*`). +- `--network_args "cross_modal_alpha="`: Optional LoRA alpha override for cross-modal modules. + +Example: +```bash +--network_dim 32 ^ +--network_alpha 16 ^ +--audio_dim 8 ^ +--audio_alpha 8 ^ +--network_args "cross_modal_dim=12" "cross_modal_alpha=12" +``` + +Result: +- Audio-only modules (`audio_attn`, `audio_ff`, etc.) → rank 8, alpha 8 +- Cross-modal modules (`audio_to_video_attn`, `video_to_audio_attn`, `av_ca_*`) → rank 12, alpha 12 +- Video modules → rank 32, alpha 16 + +Precedence is: `cross_modal_*` override > `audio_*` override > base `--network_dim` / `--network_alpha`. + +All override flags default to `None` (no override, all modules use `--network_dim`/`--network_alpha`). Not used with LyCORIS — use the LyCORIS per-module config instead. At inference, each module's rank is read from saved weight shapes (`lora_down.shape[0]`), so no flags are needed for loading. + +For AV runs where audio overfits before video, `--audio_dim 8 --audio_alpha 8` can be combined with lower `--audio_lr`, `--audio_loss_balance_mode ema_mag`, and modality freezing. + +#### Adaptive LoRA Rank + +Implemented only for standard LoRA (`networks.lora_ltx2` / `networks.lora`). +Related paper: [Not All Layers Are Created Equal: Adaptive Rank Allocation in Personalized Diffusion Models](https://arxiv.org/abs/2603.21884). + +- `--network_args "adaptive_rank=True"`: Enable adaptive rank. +- `--network_args "adaptive_rank_target="`: Target effective rank. Default: each module's base rank. +- `--network_args "adaptive_rank_weight="`: Rank regularization weight. Default: `1e-4` when enabled. +- `--network_args "adaptive_rank_budget="`: Shared target for the sum of expected ranks. +- `--network_args "adaptive_rank_budget_ratio="`: Use `total_max_rank * ratio` when `adaptive_rank_budget` is unset. +- `--network_args "adaptive_rank_estimate=True"`: Use `/ltx2_estimate.json`. If the file is missing, it is generated from the current training args before rank allocation is applied. +- `--network_args "adaptive_rank_estimate_report="`: Override the estimate report path. +- `--network_args "adaptive_rank_hard_prune=True"`: Rebuild modules as static LoRA during training when the prune trigger fires. +- `--network_args "adaptive_rank_finalize_start="`: Convert remaining adaptive modules to static LoRA once training progress reaches this value. + +Behavior: +- Without `adaptive_rank_hard_prune`, modules keep their configured base rank during training. +- Export writes standard LoRA weights. Inference reads per-module rank from weight shapes; no adaptive-rank runtime logic is required. +- `--save_state` also writes `adaptive_rank_runtime.json`. `--resume` restores adaptive/static module structure from it before loading model weights. +- Shared-budget loss uses the sum of expected ranks, not the final exported integer ranks. +- `adaptive_rank_budget` overrides `adaptive_rank_budget_ratio`. +- With `audio_dim` / `cross_modal_dim`, each module keeps its own local maximum rank. +- Estimate score lookup reads `module_scores`, or `top_modules` as fallback, keyed by `module_path`. + +CLI example: +```bash +--network_dim 64 ^ +--network_args "adaptive_rank=True" "adaptive_rank_target=16" "adaptive_rank_weight=1e-4" +``` + +Estimate-driven example: +```bash +--network_dim 64 ^ +--network_args "adaptive_rank=True" "adaptive_rank_budget_ratio=0.35" "adaptive_rank_estimate=True" "adaptive_rank_hard_prune=True" +``` + +Notes: +- Logged metrics include `loss/adaptive_rank`, `adaptive_rank/mean_effective_rank`, `adaptive_rank/mean_expected_rank`, `adaptive_rank/mean_target_rank`, and, when a shared budget is enabled, `adaptive_rank/expected_rank_sum` and `adaptive_rank/target_budget`. + +#### Per-Module LoRA Dropout + +Keep the existing global LoRA dropout as the default, but optionally override it per modality through `--network_args`. + +- `--network_dropout `: Base dropout for all LoRA modules. +- `--network_args "audio_dropout="`: Optional dropout override for audio-only modules. +- `--network_args "video_dropout="`: Optional dropout override for non-audio video modules. +- `--network_args "cross_modal_dropout="`: Optional dropout override for cross-modal modules (`audio_to_video`, `video_to_audio`, `av_ca_*`). + +Example: +```bash +--network_dropout 0.10 ^ +--network_args "audio_dropout=0.15" "video_dropout=0.05" "cross_modal_dropout=0.20" +``` + +Result: +- Audio-only modules → dropout `0.15` +- Video-only modules → dropout `0.05` +- Cross-modal modules → dropout `0.20` +- If no per-modality override is provided, modules keep the global `--network_dropout` + +Precedence is: `cross_modal_dropout` override > `audio_dropout` override for audio-only modules > `video_dropout` override for video-only modules > global `--network_dropout`. + +#### Preservation & Regularization + +Optional techniques that constrain how the LoRA modifies the base model. All are disabled by default with zero overhead. + +**Blank Prompt Preservation** — Prevents the LoRA from altering the model's blank-prompt output (used as the CFG baseline during inference): +```bash +--blank_preservation --blank_preservation_args multiplier=1.0 +``` + +**Differential Output Preservation (DOP)** — Prevents the LoRA from altering class-prompt output, scoping the LoRA effect to the trigger word only: +```bash +--dop --dop_args class=woman multiplier=1.0 +``` +The `class` parameter should be a general description without your trigger word (e.g., `woman`, `cat`, `landscape`). + +**Prior Divergence** — Encourages the LoRA to produce outputs that differ from the base model on training prompts, discouraging overly weak LoRA effects: +```bash +--prior_divergence --prior_divergence_args multiplier=0.1 +``` + +**Audio DOP** — Preserves the base model's audio predictions on non-audio training steps. Requires `--ltx2_mode av`. On each non-audio batch, constructs silence audio latents, runs the transformer with LoRA OFF and ON, and minimizes MSE on the audio branch only. Zero cost on audio batches. Mutually exclusive with `--audio_silence_regularizer`. +```bash +--audio_dop --audio_dop_args multiplier=0.5 +``` + +**TARP (Temporally Aligned RoPE and Partitioning)** — Windowed cross-attention masks that restrict each video frame to temporally nearby audio tokens (A2V) and each audio token to its nearest video frame (V2A). Enforces temporal locality in the AV cross-attention without modifying model weights. Requires `--ltx2_mode av`. From [arXiv:2603.18600](https://arxiv.org/abs/2603.18600). +```bash +--tarp --tarp_args window_multiplier=3 +``` +`window_multiplier` controls the A2V window size: `s = multiplier * floor(audio_tokens / video_frames)`. Default 3 (each frame sees 3x its proportional share of audio). V2A always uses nearest-neighbour (s=1). + +TARP can be combined with `--cts_lambda_video_driven` / `--cts_lambda_audio_driven` when lip sync or cross-modal alignment is the main target. + +**DCR (Dynamic Context Routing)** — Per-sample gradient detachment in cross-attention for mixed audio/video batches. When a sample lacks audio (zero-padded) or uses a clean reference (sigma=0), DCR detaches that stream's cross-attention context, preventing gradient flow through absent or reference-only streams. Forward values are unchanged; only the gradient path is masked. Requires `--ltx2_mode av`. From [arXiv:2603.18600](https://arxiv.org/abs/2603.18600). +```bash +--dcr --dcr_args reference_detach=true +``` +`reference_detach` (default `true`) additionally detaches the reference stream when its timestep sigma is exactly 0. + +DCR can be combined with the audio-aware sampler, `--audio_loss_balance_mode ema_mag`, and per-modality caption dropout. For `av_ic` runs, keep `reference_detach=true` unless you specifically want gradients through clean reference streams. + +**AV Cross Grad Surgery** — Branch-aware gradient scaling for LTX-2 AV cross-modal K/V projections. Forward values are unchanged; the hook only scales the backward path through selected `audio_to_video_attn.to_k`, `audio_to_video_attn.to_v`, `video_to_audio_attn.to_k`, and `video_to_audio_attn.to_v` projections. This is opt-in and requires `--ltx2_mode av`. +```bash +--av_cross_grad_surgery +``` +Bare `--av_cross_grad_surgery` uses the OmniNFT-inspired A2V schedule `a2v=0:0,1-10:0.1,40-47:0.3` with `projections=k,v`. Custom schedules use `--av_cross_grad_surgery_args`: +```bash +--av_cross_grad_surgery --av_cross_grad_surgery_args a2v=0:0,1-10:0.1,40-47:0.3 v2a=40-47:0.3 projections=k,v +``` +Schedule entries are comma-separated `block:scale` or `start-end:scale` selectors. Scales must be in `[0, 1]`. Blocks not listed keep normal gradients. + +**AV Attention Loss Weighting** — Uses detached A2V/V2A cross-attention concentration to upweight selected video and audio denoising loss tokens during the existing forward pass. This is opt-in and requires `--ltx2_mode av`. +```bash +--av_attention_loss_weighting --av_attention_loss_max 1.5 --av_attention_loss_warmup_steps 400 +``` +The multiplier warms from `1.0` to `--av_attention_loss_max`; tokens without captured attention keep normal loss weight. + +**Cross-Task Synergy** — Auxiliary AV losses with one modality clean (timestep=0), intended to provide cross-modal alignment targets. Adds two extra forward passes per AV batch. From [Harmony](https://arxiv.org/abs/2511.21579). +```bash +--cts_lambda_video_driven 0.3 --cts_lambda_audio_driven 0.1 +``` +CTS can be combined with TARP. Keep it off unless AV sync or cross-modal alignment is the target and the extra compute is acceptable. + +**TREAD** - Training-time token routing for LTX token streams. This is opt-in. Enable it with `--tread`; optional settings use `--tread_args`: +```bash +--tread --tread_args selection_ratio=0.5 start_layer_idx=3 end_layer_idx=-4 +--tread --tread_args target=audio selection_ratio=0.5 start_layer_idx=3 end_layer_idx=-4 +``` +- Bare `--tread` uses defaults. +- Default `target` is `video`. `target=audio` routes audio tokens, and `target=both` routes both video and audio tokens. Audio targets require an audio-enabled LTX mode. +- Default `selection_ratio` is `0.5`. +- The default block range is `3/-4` for LTX-2.3 and `2/-2` for LTX-2.0. +- `--tread_args` accepts `target`, `selection_ratio`, `start_layer_idx`, and `end_layer_idx`; aliases are `modality`, `ratio`, `start`, and `end`. +- TREAD is training-only. Video targets require a video-enabled path; audio-only training must use `target=audio`. + +**Differential Guidance** - Prediction-relative scaling for the video/main training target. This is opt-in: +```bash +--differential_guidance +``` +It applies this transform before the normal video/main prediction loss: +```text +target = pred + scale * (target - pred) +``` +The default scale is `3.0` when enabled. Use `--differential_guidance_scale` to override it. Scale `1.0` is unchanged, values above `1.0` strengthen the target delta, and values between `0.0` and `1.0` soften it. The feature affects training loss only and does not change inference. + +| Technique | Extra forwards/step | Extra backwards/step | Starting value / multiplier | +|-----------|-------------------|---------------------|----------------------| +| `--blank_preservation` | +2 | +1 | 0.5 - 1.0 | +| `--dop` | +2 | +1 | 0.5 - 1.0 | +| `--prior_divergence` | +1 | 0 | 0.05 - 0.1 | +| `--audio_dop` | +2 (non-audio steps only) | +1 (non-audio steps only) | 0.3 - 1.0 | +| `--tarp` | 0 | 0 | N/A (mask only) | +| `--dcr` | 0 | 0 | N/A (gradient routing) | +| `--av_cross_grad_surgery` | 0 | 0 | A2V K/V: 0:0, 1-10:0.1, 40-47:0.3 | +| `--cts_lambda_*` | +1 per enabled direction | 0 | 0.1 - 0.3 | +| `--av_attention_loss_weighting` | 0 | 0 | Max 1.5, warmup 400 steps | +| `--tread` / `--tread_args` | 0 | 0 | N/A (routing only) | +| `--differential_guidance` | 0 | 0 | Default scale 3.0 when enabled; scale 1.0 = unchanged | + +> [!CAUTION] +> Some preservation techniques add transformer forward passes per step. Audio DOP costs apply only on non-audio steps. CTS adds one forward per enabled direction. TARP, DCR, AV Cross Grad Surgery, AV Attention Loss Weighting, TREAD, and Differential Guidance add no extra passes; they modify the existing forward/backward in-place. + +#### CREPA (Cross-frame Representation Alignment) + +Encourages temporal consistency across video frames by aligning DiT hidden states across frames via a small projector MLP. Only the projector is trained; all other modules stay frozen. CREPA uses hooks to capture intermediate features from the existing forward pass (no extra forward passes). Two modes are available: `dino` (based on [arXiv 2506.09229](https://arxiv.org/abs/2506.09229), aligns to pre-cached DINOv2 features from neighboring frames) and `backbone` (inspired by [SimpleTuner LayerSync](https://github.com/bghira/SimpleTuner), aligns to a deeper block of the same transformer). + +Enable with `--crepa`. All parameters are passed via `--crepa_args` as `key=value` pairs: + +```bash +accelerate launch ... ltx2_train_network.py ^ + --crepa ^ + --crepa_args mode=backbone student_block_idx=16 teacher_block_idx=32 lambda_crepa=0.1 tau=1.0 num_neighbors=2 schedule=constant warmup_steps=0 normalize=true +``` + +Optional EMA cutoff can disable the CREPA loss once the alignment score is already high enough: + +```bash +accelerate launch ... ltx2_train_network.py ^ + --crepa ^ + --crepa_args similarity_threshold=0.90 similarity_ema_decay=0.99 threshold_mode=permanent +``` + +##### CREPA CLI Flags + +| Flag | Type | Description | +|------|------|-------------| +| `--crepa` | store_true | Enable CREPA regularization | +| `--crepa_args` | key=value list | Configuration parameters (see table below) | + +##### CREPA Parameters (`--crepa_args`) + +| Parameter | Default | Description | +|-----------|---------|-------------| +| `mode` | `backbone` | Teacher signal source: `backbone` (deeper DiT block) or `dino` (pre-cached DINOv2 features) | +| `dino_model` | `dinov2_vitb14` | DINOv2 variant for dino mode. Must match the model used during caching. Options: `dinov2_vits14`, `dinov2_vitb14`, `dinov2_vitl14`, `dinov2_vitg14` | +| `student_block_idx` | 16 | Transformer block whose hidden states are aligned (0-47 for LTX-2 48-block model) | +| `teacher_block_idx` | 32 | Deeper block providing the teacher signal (backbone mode only, must be > `student_block_idx`) | +| `lambda_crepa` | 0.1 | Loss weight for CREPA term. Recommended range: 0.05–0.5 | +| `tau` | 1.0 | Temporal neighbor decay factor. Controls how much nearby frames contribute vs distant ones | +| `num_neighbors` | 2 | Number of neighboring frames on each side (K). Frame f aligns with frames f-K..f+K | +| `schedule` | `constant` | Lambda schedule over training: `constant`, `linear` (decay to 0), or `cosine` (cosine decay to 0) | +| `warmup_steps` | 0 | Steps before CREPA loss reaches full strength (linear ramp from 0) | +| `max_steps` | 0 | Total training steps for schedule computation. Auto-filled from `--max_train_steps` if not set | +| `normalize` | `true` | L2-normalize features before computing cosine similarity | +| `similarity_threshold` | off | Enables EMA cutoff when set to a value from 0 to 1. CREPA is disabled after the smoothed alignment score reaches this value | +| `similarity_ema_decay` | 0.99 | Smoothing factor for the cutoff score. Higher values react more slowly | +| `threshold_mode` | `permanent` | `permanent` keeps CREPA off after cutoff; `recoverable` can resume CREPA if the score drops again | +| `cutoff_step` | 0 | Optional global step where CREPA is disabled regardless of score. 0 keeps this disabled | + +##### CREPA Checkpoint & Resume + +- The projector weights (~33M params for backbone mode) are saved as `crepa_projector.safetensors` in the output directory alongside LoRA checkpoints. +- When resuming training with `--crepa`, projector weights are automatically loaded from `/crepa_projector.safetensors` if the file exists. +- EMA cutoff state is saved as `crepa_state.safetensors` when training state saving is enabled, so a permanent cutoff remains permanent after resume. +- The projector is **not needed at inference** — it's only used during training. + +##### CREPA Monitoring + +CREPA adds `loss/crepa` to TensorBoard/WandB logs. With EMA cutoff enabled, it also logs `crepa/weight`, `crepa/cutoff`, `crepa/alignment_score`, `crepa/similarity_self`, and `crepa/alignment_score_ema`. A healthy CREPA loss should: +- Start negative (cosine similarity is being maximized) +- Gradually decrease (more negative = stronger cross-frame alignment) +- Stabilize after warmup + +Use EMA cutoff when CREPA is helpful early but you do not want it to keep pushing already-aligned clips for the whole run. Start with a high threshold such as 0.90-0.95; leave it off if you want the existing CREPA behavior. + +##### CREPA Compatibility + +- Works with block swap (`--blocks_to_swap`) — hooks fire when each block executes regardless of CPU offloading. +- Works with all preservation techniques (blank preservation, DOP, prior divergence). +- Works with gradient checkpointing. +- Projector params are included in gradient clipping alongside LoRA params. + +##### Caching DINOv2 Features (Dino Mode) + +Dino mode requires pre-cached DINOv2 features. Run this **after latent caching** (cache paths are derived from latent cache files). DINOv2 is not loaded during training; only cached tensors are read, so the DINO model itself adds no training VRAM. + +```bash +python ltx2_cache_dino_features.py ^ + --dataset_config dataset.toml ^ + --dino_model dinov2_vitb14 ^ + --dino_batch_size 16 ^ + --device cuda ^ + --skip_existing +``` + +- `--dino_model`: DINOv2 variant — `dinov2_vits14` (384d), `dinov2_vitb14` (768d, default), `dinov2_vitl14` (1024d), `dinov2_vitg14` (1536d). +- `--dino_batch_size`: Frames per forward pass. Reduce if OOM (default: 16). +- `--dino_repo_path`: Local `facebookresearch/dinov2` clone containing `hubconf.py`. Uses `torch.hub` with `source="local"` and avoids a GitHub fetch. +- `--torch_hub_dir`: Torch hub cache directory. Use this when the DINOv2 repo/weights are already pre-populated in a local cache. +- `--skip_existing`: Skip items that already have cached features. +- `--atomic_cache_writes`: Opt-in safety mode. Writes each DINO cache through a temporary sibling file before replacing the final path. + +Output: `*_ltx2_dino.safetensors` files alongside your latent caches, containing per-frame patch tokens `[T, N_patches, D]`. For `dinov2_vitb14` at 518px input: `N_patches=1369`, `D=768`, so each frame adds ~2MB (float16). Disk usage scales linearly with frame count. + +**Precaching preservation prompts:** Blank preservation and DOP require Gemma to encode their prompts at training startup. To avoid loading Gemma during training, precache the embeddings during the text encoder caching step: +```bash +python ltx2_cache_text_encoder_outputs.py --dataset_config ... --ltx2_checkpoint ... --gemma_root ... ^ + --precache_preservation_prompts --blank_preservation --dop --dop_class_prompt "woman" +``` +Then add the `--use_precached_preservation` flag during training: +```bash +python ltx2_train_network.py ... ^ + --blank_preservation --dop --dop_args class=woman ^ + --use_precached_preservation +``` +The cache file is saved to `/ltx2_preservation_cache.pt` by default (same directory as your dataset cache). Use `--preservation_prompts_cache ` to override the location in either command. Prior divergence does not need precaching (it uses the training batch's own embeddings). + +#### Self-Flow (Self-Supervised Flow Matching) + +**Self-Flow** is intended to reduce drift from the pretrained model's internal representations. It aligns student features (shallower block) against teacher features (deeper block) using cosine similarity, with dual-timestep noising to create a student-teacher gap. The default `teacher_mode=base` uses the **frozen pretrained model** as teacher by zeroing LoRA multipliers for the teacher forward pass, avoiding a separate teacher-weight copy. An EMA-based teacher (`teacher_mode=ema`) is also available for LoRA-aware distillation. The optional **temporal extension** adds frame-neighbor and motion-delta consistency terms. Based on [arXiv 2603.06507](https://arxiv.org/abs/2603.06507). + +Enable with `--self_flow`. Supported in `--ltx2_mode video` and `--ltx2_mode av` (video branch only in AV mode). All parameters are passed via `--self_flow_args` as `key=value` pairs: + +```bash +# Recommended default: base-model teacher, token-level alignment only +accelerate launch ... ltx2_train_network.py ^ + --self_flow ^ + --self_flow_args teacher_mode=base student_block_ratio=0.3 teacher_block_ratio=0.7 lambda_self_flow=0.1 mask_ratio=0.1 dual_timestep=true + +# With temporal consistency (hybrid = frame alignment + motion delta) +accelerate launch ... ltx2_train_network.py ^ + --self_flow ^ + --self_flow_args lambda_self_flow=0.1 temporal_mode=hybrid lambda_temporal=0.1 lambda_delta=0.05 num_neighbors=2 temporal_granularity=frame +``` + +##### CLI Flags + +| Flag | Type | Description | +|------|------|-------------| +| `--self_flow` | store_true | Enable Self-Flow regularization | +| `--self_flow_args` | key=value list | Configuration parameters (see table below) | + +##### Self-Flow Parameters (`--self_flow_args`) + +| Parameter | Default | Description | +|-----------|---------|-------------| +| `teacher_mode` | `base` | Teacher source: `base` (frozen pretrained; zero LoRA multipliers during teacher pass, no separate teacher-weight copy), `ema` (EMA over all LoRA params), `partial_ema` (EMA over teacher block's LoRA params only) | +| `student_block_idx` | `16` | Student feature block index (0-based; overridden by `student_block_ratio` when set) | +| `teacher_block_idx` | `32` | Teacher feature block index (must be `> student_block_idx`; overridden by `teacher_block_ratio` when set) | +| `student_block_ratio` | `None` | Ratio-based student layer selection. Resolves to `floor(ratio * depth)`. Takes priority over `student_block_idx`. | +| `teacher_block_ratio` | `None` | Ratio-based teacher layer selection. Resolves to `ceil(ratio * depth)`. Takes priority over `teacher_block_idx`. | +| `student_block_stochastic_range` | `0` | Randomly vary the student capture block ±N blocks each step. `0` = fixed block. Adds regularization diversity; note a single projector is shared across all depth variants. | +| `lambda_self_flow` | `0.1` | Loss weight for the video token-level representation alignment term | +| `lambda_audio` | `0.0` | Loss weight for audio representation alignment. When `> 0`, captures audio hidden states from the same student/teacher blocks and aligns them via a separate audio projector MLP. Requires `--ltx2_mode av`. `0` = disabled (backward compatible). | +| `mask_ratio` | `0.10` | Token mask ratio for dual-timestep mixing. Valid range: `[0.0, 0.5]` | +| `frame_level_mask` | `false` | When `true`, mask whole latent frames instead of individual tokens. More semantically coherent masking for video. | +| `mask_focus_loss` | `false` | When `true`, compute the representation loss only on masked (higher-noise) tokens. Default: loss over all tokens. | +| `max_loss` | `0.0` | Cap Self-Flow loss magnitude by rescaling if total loss exceeds this value. `0` = disabled. Useful to prevent Self-Flow from dominating the main task loss early in training. | +| `temporal_mode` | `off` | Temporal extension mode: `off`, `frame`, `delta`, or `hybrid` | +| `lambda_temporal` | `0.0` | Loss weight for frame-level temporal neighbor alignment | +| `lambda_delta` | `0.0` | Loss weight for frame-delta alignment (motion consistency) | +| `temporal_tau` | `1.0` | Neighbor decay factor for `frame` / `hybrid` temporal alignment | +| `num_neighbors` | `2` | Number of temporal neighbors on each side used by `frame` / `hybrid` mode | +| `temporal_granularity` | `frame` | Temporal loss granularity: `frame` (mean-pooled per frame) or `patch` (preserve spatial tokens) | +| `patch_spatial_radius` | `0` | In `temporal_granularity=patch`, local spatial neighborhood radius for teacher patch matching (`0` = strict same-patch only) | +| `patch_match_mode` | `hard` | Patch-neighborhood matching mode: `hard` (best patch in window) or `soft` (softmax-weighted neighborhood match) | +| `patch_match_temperature` | `0.1` | Soft neighborhood matching temperature when `patch_match_mode=soft` | +| `delta_num_steps` | `1` | Number of temporal delta steps included in the delta loss (`1` = adjacent frames only) | +| `motion_weighting` | `none` | Temporal weighting mode: `none` or `teacher_delta` | +| `motion_weight_strength` | `0.0` | Strength of teacher-delta motion weighting for temporal terms | +| `temporal_schedule` | `constant` | Schedule applied to **all** Self-Flow lambdas (`lambda_self_flow`, `lambda_audio`, `lambda_temporal`, `lambda_delta`): `constant`, `linear` decay, or `cosine` decay | +| `temporal_warmup_steps` | `0` | Steps to linearly ramp all lambdas up from zero to full weight | +| `temporal_max_steps` | `0` | Steps at which `linear` / `cosine` decay reaches zero. `0` = no decay | +| `teacher_momentum` | `0.999` | EMA momentum for teacher updates (`ema` / `partial_ema` modes only). Valid range: `[0.0, 1.0)` | +| `teacher_update_interval` | `1` | Update EMA teacher every N optimizer steps | +| `projector_hidden_multiplier` | `1` | Projector hidden width multiplier vs model inner dim | +| `projector_activation` | `silu` | Projector MLP activation function: `silu` or `gelu` | +| `projector_lr` | `None` | Optional projector-specific learning rate. Defaults to `--learning_rate` when unset | +| `loss_type` | `negative_cosine` | `negative_cosine` or `one_minus_cosine` | +| `dual_timestep` | `true` | Enable dual-timestep noising | +| `tokenwise_timestep` | `true` | Use per-token timesteps (otherwise per-sample averaged timestep) | +| `offload_teacher_features` | `false` | Offload cached teacher features to CPU to reduce VRAM | +| `offload_teacher_params` | `false` | Offload EMA teacher parameters to CPU (saves VRAM, slower teacher forward pass; `ema` / `partial_ema` only) | + +##### Notes + +- Supported modes: `--ltx2_mode video`, `--ltx2_mode av`. In AV mode, video alignment is always active when `lambda_self_flow > 0`; audio alignment is active when `lambda_audio > 0`. +- Image-like training is supported through single-frame samples in `--ltx2_mode video` (set `temporal_mode=off` unless you intentionally want temporal terms to be inactive on image batches). +- Cost: one extra teacher forward pass per train step. `teacher_mode=base` reuses the existing model with LoRA multipliers zeroed instead of keeping a separate teacher-weight copy. +- Teacher modes: `base` gives the largest student-teacher gap (pretrained vs LoRA-finetuned); `ema` / `partial_ema` give a moving target that shrinks as training converges. +- Temporal extension: when `temporal_mode != off`, Self-Flow reshapes hidden states into latent frames and adds frame-neighbor and/or frame-delta consistency losses on top of the base token alignment loss. +- Granularity: `temporal_granularity=frame` uses mean-pooled per-frame features (cheaper, coarser). `temporal_granularity=patch` keeps spatial tokens for stronger temporal matching. +- Local patch matching: when `temporal_granularity=patch` and `patch_spatial_radius > 0`, each student patch can align to the best teacher patch inside a local spatial window, which is more tolerant to small motion and camera drift than strict same-patch matching. +- Soft matching: `patch_match_mode=soft` replaces hard local best-match selection with softmax-weighted neighborhood matching for smoother gradients. +- Multi-step motion: `delta_num_steps > 1` extends the delta loss beyond adjacent frames using exponentially decayed step weights. +- Motion-aware weighting: `motion_weighting=teacher_delta` upweights temporally active teacher regions, focusing the temporal loss on moving content. +- Scheduling: `temporal_schedule`, `temporal_warmup_steps`, and `temporal_max_steps` apply to all Self-Flow lambdas — `lambda_self_flow`, `lambda_audio`, `lambda_temporal`, and `lambda_delta` — uniformly. +- AV audio: when `lambda_audio > 0`, AV mode builds a separate dual-timestep student audio view and a cleaner teacher audio view, matching the video Self-Flow teacher/student asymmetry. +- Validation: the primary validation loss uses the normal homogeneous noising path. `val_self_flow_loss`, when logged, is a separate diagnostic and is not added to `val_loss`. +- State files (Accelerate `*-state` folder): `self_flow_projector.safetensors`, `self_flow_teacher_ema.safetensors` (EMA state only saved when `teacher_mode=ema` or `partial_ema`). +- Resume: both state files are loaded automatically when present. Loading EMA state with `teacher_mode=base` emits a warning and is ignored. +- Logged metrics: `loss/self_flow`, `self_flow/cosine`, `self_flow/audio_cosine`, `self_flow/frame_cosine`, `self_flow/delta_cosine`, `self_flow/lambda_self_flow`, `self_flow/lambda_audio`, `self_flow/lambda_temporal`, `self_flow/lambda_delta`, `self_flow/masked_token_ratio`, `self_flow/audio_masked_token_ratio`, `self_flow/tau_mean`, `self_flow/tau_min_mean`, `self_flow/audio_tau_mean`, `self_flow/audio_tau_min_mean`. + +#### HFATO (High-Frequency Awareness Training Objective) + +Adapted from [ViBe (arXiv 2603.23326)](https://arxiv.org/abs/2603.23326). Experimental — not yet validated on LTX-2. + +**HFATO** is a training objective designed for image-only fine-tuning of video models. Before adding noise, clean latents are spatially degraded via downsample-upsample, destroying high-frequency details. The model is then supervised to reconstruct the original clean latents (x₀-prediction loss instead of standard velocity loss). Can be combined with the Relay LoRA workflow below for two-stage image-only training. + +Enable with `--hfato`. Parameters are passed via `--hfato_args` as `key=value` pairs. Incompatible with `--ic_lora_strategy v2v`. + +```bash +accelerate launch ... ltx2_train_network.py ^ + --hfato ^ + --hfato_args scale_factor=0.5 +``` + +##### CLI Flags + +| Flag | Type | Description | +|------|------|-------------| +| `--hfato` | store_true | Enable HFATO loss | +| `--hfato_args` | key=value list | Configuration parameters (see table below) | + +##### HFATO Parameters (`--hfato_args`) + +| Parameter | Default | Description | +|-----------|---------|-------------| +| `scale_factor` | `0.5` | Spatial downsample ratio. `0.5` = halve each spatial dimension. Lower values destroy more high-frequency info and force stronger reconstruction. `0.25` is more aggressive. | +| `interpolation` | `bilinear` | Interpolation mode for downsample-upsample: `bilinear`, `nearest`, or `bicubic` | +| `probability` | `1.0` | Per-step probability of applying HFATO. `1.0` = always. Values `< 1.0` mix HFATO and standard flow matching steps. | + +##### Relay LoRA Workflow (Image-Only Training) + +Two-stage training strategy for adapting a video model using only images: + +1. **Stage 1 (Modality Bridge)**: Train a LoRA on low-resolution images using standard flow matching. Bridges the image-video modality gap. +2. **Merge**: Merge the Stage 1 LoRA into the base model checkpoint. +3. **Stage 2 (Detail Enhancement)**: Train a new LoRA on high-resolution images with `--hfato`, using the merged checkpoint. +4. **Inference**: Load the original base model with only the Stage 2 LoRA. Stage 1 is discarded. + +```bash +# Stage 1: standard LoRA on low-res images +accelerate launch ... ltx2_train_network.py ^ + --ltx2_checkpoint base_model.safetensors ^ + --network_dim 32 --output_dir stage1_output/ + +# Merge Stage 1 into base +python ltx2_merge_lora_to_model.py ^ + --dit base_model.safetensors ^ + --lora_weight stage1_output/last.safetensors ^ + --save_merged_model merged_model.safetensors + +# Stage 2: HFATO on high-res images using merged base +accelerate launch ... ltx2_train_network.py ^ + --ltx2_checkpoint merged_model.safetensors ^ + --hfato --hfato_args scale_factor=0.5 ^ + --network_dim 32 --output_dir stage2_output/ + +# Inference: original base + Stage 2 LoRA only +python ltx2_generate_video.py ^ + --ltx2_checkpoint base_model.safetensors ^ + --lora_weight stage2_output/last.safetensors +``` + +The resulting LoRA is standard — no inference pipeline changes. In the ViBe Relay LoRA design, Stage 1 is used only to train the Stage 2 base; inference loads the original base model plus the Stage 2 LoRA, so the low-resolution bridge is not part of the deployed model. + +HFATO can also be used standalone (without relay) as a spatial detail objective for image or video training. + +#### Latent Temporal Objectives + +Adds two optional training-only terms to the LTX-2 video loss. The saved LoRA/checkpoint is loaded normally at inference. + +- `--latent_temporal_weighting`: computes clean-latent frame deltas `||z[t+1] - z[t]||` and maps them to per-frame multipliers for the denoising loss. +- `--latent_delta_loss`: computes `x0_pred = noisy - sigma * video_pred` or uses predicted velocity, then matches temporal derivatives to the clean latent target: `Delta pred ~= Delta target`. + +Paper basis: `--latent_temporal_weighting` follows Latent Temporal Discrepancy ([arXiv 2601.20504](https://arxiv.org/abs/2601.20504)). `--latent_delta_loss` is an LTX-2-specific auxiliary objective in this trainer, not a direct reproduction of a paper method. + +Usage: + +```bash +# LoRA defaults +accelerate launch ... ltx2_train_network.py ^ + --latent_temporal_weighting ^ + --latent_temporal_weighting_args alpha=0.5 mode=log normalize=mean clip_min=0.5 clip_max=2.0 ^ + --latent_delta_loss ^ + --latent_delta_loss_args weight=0.03 order=1 target=x0 sigma_min=0.05 sigma_max=0.85 +``` + +When both flags are off, the trainer does not attach latent-temporal context and the training loss path is unchanged. + +Behavior: + +- `order=1` matches first-order frame deltas; `order=2` matches second-order deltas; `order=1+2` uses both. +- `sigma_min` / `sigma_max` gate only the extra delta loss. +- Delta loss matches target deltas; it does not minimize motion magnitude. +- HFATO uses its own x0 reducer, so latent temporal weighting is not applied to HFATO's primary loss. +- Token/reference IC paths are skipped unless they expose 5D video predictions. +- Logged metrics: `latent_temporal_weight_mean`, `latent_temporal_weight_min`, `latent_temporal_weight_max`, `loss/latent_delta`, `loss/latent_accel`, `loss/latent_temporal_extra`. + +##### Weighting Args + +| Parameter | Default | Description | +|-----------|---------|-------------| +| `alpha` | `0.5` | Motion-weight strength | +| `mode` | `log` | Motion score transform: `log` or `linear` | +| `normalize` | `mean` | Score normalization | +| `clip_min` | `0.5` | Lower clamp before final mean rescale | +| `clip_max` | `2.0` | Upper clamp before final mean rescale | + +##### Delta Loss Args + +| Parameter | Default | Description | +|-----------|---------|-------------| +| `weight` | `0.03` | Extra loss multiplier | +| `order` | `1` | `1`, `2`, `1+2`, or `both` | +| `target` | `x0` | Match derivatives of `x0` or raw `velocity` | +| `sigma_min` | `0.0` | Minimum sigma where the extra loss is active | +| `sigma_max` | `1.0` | Maximum sigma where the extra loss is active | +| `second_order_weight` | `0.5` | Multiplier for `order=2` term | +| `loss_type` | `mse` | `mse`, `l1`, `huber`, or `smooth_l1` | +| `huber_delta` | `1.0` | Huber beta for `huber` / `smooth_l1` | + +#### Standalone Inference Overrides + +`ltx2_generate_video.py` accepts a few standalone-inference-only overrides that are not part of the training sample table: + +- `--vae`: Use a separate VAE checkpoint for inference. If omitted, `--ltx2_checkpoint` is used for both DiT and VAE loading. +- `--vae_dtype`: Override the VAE runtime dtype for inference. If omitted, the script uses its default VAE dtype (`bfloat16`). +- `--reference_image`: Apply one global I2V reference image to all prompts in the current inference run. +- `--reference_video`: Apply one global V2V reference video to all prompts in the current inference run. +- If both `--reference_image` and `--reference_video` are supplied, `--reference_video` takes priority. +- Global `--reference_image` / `--reference_video` overrides replace conflicting per-prompt `image_path` / `v2v_ref_path` entries loaded from prompt files, and also clear any cached reference latents tied to those prompt entries before sampling. +- If the path passed to `--reference_image` has a video filename extension, the script treats it as a V2V reference and routes it through the video-reference path. + +#### Audio Quality Metrics + +Enable with `--audio_metrics`. All logic is in `audio_metrics.py`. When disabled, the trainer does not run the audio-metrics code path. + +**Per-step** (latent-space, enabled by default with `--audio_metrics`): + +| Key | Description | +|-----|-------------| +| `audio_metrics/latent_fd` | Running Frechet distance between pred/target latent distributions (every 50 steps) | +| `audio_metrics/temporal_coherence` | Cosine similarity between adjacent audio latent frames | +| `audio_metrics/av_latent_sync` | Pearson correlation between audio and video per-frame energy | + +**Periodic** (mel-space, opt-in — decodes 1 sample per batch through AudioDecoder): +```bash +--audio_metrics --audio_metrics_args mel_metrics=true mel_compute_every=100 +``` + +| Key | Description | +|-----|-------------| +| `audio_metrics/spectral_convergence` | `\|\|S_pred - S_target\|\|_F / \|\|S_target\|\|_F` | +| `audio_metrics/mcd_db` | Mel Cepstral Distortion (13 DCT coefficients, dB) | +| `audio_metrics/log_spectral_distance_db` | Per-frame log-spectral distance (dB) | + +**Sampling-time** (embedding-space, opt-in — runs on generated waveforms during `sample_images`): +```bash +--audio_metrics --audio_metrics_args clap_similarity=true av_onset_alignment=true +``` + +| Key | Description | Requires | +|-----|-------------|----------| +| `sample_audio/clap_similarity` | CLAP audio-text cosine similarity | transformers (already a dep) | +| `sample_audio/av_onset_alignment` | Correlation between audio energy onsets and video motion | None | + +CLAP model is lazy-loaded on first sample, offloaded to CPU between uses. + +#### Timestep Sampling + +See also the [timestep bucketing documentation](./advanced_config.md) for advanced timestep bucketing options. + +- `--timestep_sampling shifted_logit_normal`: Default LTX-2 method. Uses a shifted logit-normal distribution where the shift is computed from latent sequence length. In normal video/AV training this means `latent_frames × latent_height × latent_width`; only `--ltx2_mode audio` uses the audio-only sequence-length path described below. +- `--timestep_sampling uniform`: Uniform sampling from [0, 1]. +- `--logit_std`: Standard deviation for the logit-normal distribution (default: 1.0). Only used with `shifted_logit_normal`. +- `--min_timestep` / `--max_timestep`: Optional timestep range constraints. By default LTX-2 scales the sampled sigma into this range; with `--preserve_distribution_shape`, it rejection-samples from the original distribution and keeps only values inside the range. +- `--num_timestep_buckets`: Stratified timestep buckets are honored by LTX-2 `shifted_logit_normal` and `uniform` sampling. +- `--shifted_logit_mode legacy|stretched`: Sigma sampler variant (default: auto by `--ltx_version`; 2.0→`legacy`, 2.3→`stretched`). + - `legacy`: `sigmoid(N(shift, std))`. Original behavior. + - `stretched`: Normalizes samples between the 0.5th and 99.9th percentiles of the distribution, reflects values below `eps` for numerical stability, and replaces a fraction of samples with uniform draws to prevent distribution collapse at high token counts. +- `--shifted_logit_eps`: Reflection floor and uniform lower bound for `stretched` mode (default: `1e-3`). +- `--shifted_logit_uniform_prob`: Fraction of samples replaced with uniform `[eps, 1]` draws (default: `0.1`). +- `--shifted_logit_shift`: Override the auto-calculated shift value. Lower values (e.g., `0.0`) produce a symmetric distribution centered on medium noise (σ≈0.5) for learning fine details. Higher values (e.g., `2.0`) heavily right-skew the distribution toward high noise (σ≈0.9+) for learning global structure. If unset, it is computed dynamically from sequence length. By default, non-audio training uses the raw linear formula below (so short or long sequences can fall outside the anchor values), while `--ltx2_mode audio` clamps the auto-computed shift to the configured min/max shift bounds. +- `--shifted_logit_clamp_auto_shift`: Clamp non-audio auto-computed shifts instead of extrapolating outside the anchor range. This does not affect explicit `--shifted_logit_shift`. +- `--shifted_logit_min_shift` / `--shifted_logit_max_shift`: Clamp bounds for auto-computed shifts (defaults: `0.95` / `2.05`). Audio mode always applies these bounds to auto shifts; non-audio mode applies them only with `--shifted_logit_clamp_auto_shift`. + +> [!NOTE] +> The `shifted_logit_normal` auto-shift uses a linear formula anchored at 0.95 for 1024 tokens and 2.05 for 4096 tokens, based on sequence length. By default, non-audio training extrapolates this formula outside those anchor points for shorter/longer sequences; for example, a single 768x768 image has latent sequence length `1 x (768/32) x (768/32) = 576`, which gives shift `0.7896`. In `--ltx2_mode audio`, the auto-computed shift is clamped to the configured min/max shift bounds, defaulting to `[0.95, 2.05]`. +> In `--ltx2_mode audio`, `shifted_logit_normal` still needs a sequence length to compute the shift, but there is no real video spatial dimension. Using full video resolution would inflate the sequence length and skew the shift upward. Instead, `--audio_only_sequence_resolution` (default `64`) provides a small fixed spatial footprint (4 tokens/frame), keeping the shift dominated by the temporal dimension (audio duration/FPS) which actually matters. +> In joint AV training (`--ltx2_mode av`), the auto shift still comes from the video latent geometry; the presence of audio latents does not change the shift calculation. + +#### LoRA Targets + +Use `--lora_target_preset` to control which layers LoRA targets. For custom layer patterns and `--network_args` format, see the [LoRA documentation](./advanced_config.md#lora): + +| Preset | Layers | Modality scope | Use Case | +|--------|--------|----------------|----------| +| `t2v` (default) | All attention (`to_q`, `to_k`, `to_v`, `to_out.0`) | Video + audio + cross-modal | Text-to-video default | +| `v2v` | All attention + video FFN + audio FFN | Video + audio + cross-modal | Video-to-video / IC-LoRA style | +| `video_sa` | Video self-attention (`attn1`) | Video only | Spatially-aligned controls (depth, pose, canny, inpaint) | +| `video_sa_ff` | Video self-attention + video FFN (`attn1`, `ff`) | Video only | Controls needing more capacity (local edit, cut-on-action) | +| `video_sa_ca_ff` | Video self-attention + cross-attention + video FFN (`attn1`, `attn2`, `ff`) | Video only | Text-guided controls (video detailing, camera-from-image, sparse tracks) | +| `audio` | Audio attn/FFN only | Audio only | Audio-only training (auto-selected when `--ltx2_mode audio`) | +| `audio_v2a` | Audio attn/FFN + `video_to_audio_attn` | Audio + V2A cross-modal | Audio preset plus `video_to_audio_attn` (audio queries over video tokens) | +| `audio_ref_ic` | Audio attn/FFN + bidirectional AV cross-modal | Audio + cross-modal | Audio-reference IC-LoRA | +| `av_ic` | All attention + video FFN + audio FFN (same as `v2v`) | Video + audio + cross-modal | Joint AV IC-LoRA. Use `--av_cross_attention_mode` for directional variants and `--av_multi_ref` when configuring a multi-reference AV IC run | +| `video_ref_only_av` | All attention + video FFN + audio FFN (same as `v2v`) | Video + audio + cross-modal | AV training with reference video only; target audio is still generated | +| `full` | All linear layers for LoRA targeting | Video + audio + cross-modal | Maximum expressiveness, larger file size | + +**Modality scope matters when training on an AV checkpoint.** The `t2v`, `v2v`, `av_ic`, and `full` presets create LoRA weights for audio and cross-modal layers. If those layers receive no audio training signal (e.g., image/video-only dataset), the LoRA weights for audio modules are initialized but never meaningfully updated — applying such a LoRA can degrade the base model's audio capabilities. Use a `video_*` preset to restrict LoRA to video-branch modules only, leaving audio layers completely untouched. Connector layers (`Embeddings1DConnector`) are excluded by default; use `--train_connectors` to include them (see below). + +The `audio` preset excludes `video_to_audio_attn`; `audio_v2a` includes it. Choose `audio_v2a` when the audio-side LoRA should also adapt how audio queries over video tokens. Choose `audio` when the run should leave `video_to_audio_attn` weights at base-model values — for example when later merging this LoRA with another LoRA that owns those layers. + +To use custom layer patterns instead of a preset, use `--network_args`: +```bash +--network_args "include_patterns=['.*\.to_k$','.*\.to_q$','.*\.to_v$','.*\.to_out\.0$','.*\.ff\.net\.0\.proj$','.*\.ff\.net\.2$']" +``` +Custom `include_patterns` override any preset. +When `include_patterns` is set (either explicitly or via a preset), only modules matching at least one pattern are targeted (strict whitelist behavior). Use `--lora_target_preset full` to target all linear layers. + +#### LoRA Target Estimation (`ltx2_estimate.py`) + +`ltx2_estimate.py` runs the LTX forward/loss path on cached training batches and accumulates squared gradients ("Fisher-style importance") for LoRA-targetable weights. + +- It uses `setup_parser_common()` plus `ltx2_setup_parser()`, so the normal LTX argument surface is available. In the estimator path, attention backend selection (`--sdpa`, `--flash_attn`, `--flash3`, `--xformers`), `--blocks_to_swap`, `--gradient_checkpointing`, `--blockwise_checkpointing`, `--compile`, `--fp8_base` / `--fp8_scaled`, `--nf4_base`, and `--split_attn` are applied. +- It requires `--dataset_config` and cached dataset items. If the dataset group has no training items, it exits with `No training items found in the dataset. Create latent/text caches first.` +- It keeps up to `--estimation_batches` batches. Batches without 5D `latents` are skipped. +- If `--network_weights` is set, the estimator attaches that LoRA to the transformer and scores the LoRA weights from the attached network (`candidate_source = "network"`). +- If `--network_weights` is not set, it scores LoRA-targetable linear weights from the transformer itself (`candidate_source = "base_model"`). +- If `--base_weights` is set, those weights are merged into the transformer before estimation. +- Unless `--estimation_keep_caption_dropout` is set, the estimator temporarily forces `caption_dropout_rate = 0`. +- `--estimation_block_window` only affects the base-model path: it groups candidate weights by transformer block and enables one window of blocks per backward pass. When `--network_weights` is used, all network candidates are scored in one pass. + +Example: + +```bash +python ltx2_estimate.py ^ + --dataset_config dataset.toml ^ + --ltx2_checkpoint /path/to/ltx-2.3.safetensors ^ + --mixed_precision bf16 ^ + --ltx_version 2.3 ^ + --ltx2_mode av ^ + --network_module networks.lora_ltx2 ^ + --network_weights output/your_lora.safetensors ^ + --estimation_batches 8 ^ + --estimation_output output/ltx2_estimate.json ^ + --flash_attn --fp8_base --fp8_scaled --blocks_to_swap 10 --gradient_checkpointing +``` + +The output is a JSON report written to `--estimation_output` or, if omitted, `/ltx2_estimate.json`. + +- `meta`: run configuration, timing, applied / merged weights, and `candidate_source` +- `summary`: `candidate_modules`, `candidate_params`, `total_fisher_sum`, and `recommended_preset` +- `family_scores`: aggregate scores by module family such as `video_self_attn` and `video_cross_attn` +- `preset_scores`: aggregate scores for the preset candidates available in the current `ltx_mode` +- `module_scores`: per-module score rows keyed by `module_path` +- `top_modules`: highest-ranked individual weights + +`recommended_preset` is selected as follows: + +- Pick the smallest preset whose `fisher_share` reaches `--estimation_target_coverage` +- If no preset reaches that threshold, pick the preset with the highest `efficiency` + +#### Connector LoRA (`--train_connectors`) + +Text connectors are 8-layer transformer blocks (in LTX-2.3) between Gemma and the denoising transformer. They transform text embeddings before they reach the denoising model. `--train_connectors` includes these modules in LoRA training alongside the main transformer. + +**Usage:** Cache with `--cache_before_connector`, train with `--train_connectors`. The same `--lora_target_preset` patterns apply to both transformer and connector layers. Connector and transformer LoRA weights are saved in one file. At inference and in ComfyUI (after `convert_lora_to_comfy.py`), connector weights are auto-detected and applied. + +**Notes:** Adds ~3.8 GB VRAM (bf16) for the frozen connector weights. Not compatible with LyCORIS. Connectors have `attn1` and `ff` only (no `attn2`). + +#### IC-LoRA / Video-to-Video Training + +IC-LoRA (In-Context LoRA) trains the model to generate video conditioned on a reference image or video. + +Reference frames are encoded as clean latent tokens (timestep=0) and concatenated with noisy target tokens during training. The model attends across both sequences, using the reference as conditioning context. At inference, the same concatenation scheme is applied. Position embeddings are computed separately for reference and target, allowing different spatial resolutions via `--reference_downscale`. + +##### Step 1: Prepare Dataset + +Create a dataset with a matching reference/source directory. For both video and image IC-LoRA datasets, use `reference_directory`. Each reference file must share the same filename stem as its corresponding training sample: + +``` +videos/ references/ + scene_001.mp4 scene_001.png # reference for scene_001 + scene_002.mp4 scene_002.jpg + scene_003.mp4 scene_003.mp4 # video references also work +``` + +References can be images (single frame) or videos (multiple frames). + +##### Step 2: Dataset Config + +Add `reference_cache_directory` plus the matching source directory key to your TOML config: + +```toml +[general] +resolution = [768, 512] +caption_extension = ".txt" +batch_size = 1 +enable_bucket = true +cache_directory = "cache" +reference_cache_directory = "cache_ref" + +[[datasets]] +video_directory = "videos" +reference_directory = "references" +target_frames = [1, 17, 33] +``` + +For image datasets, use `reference_directory` as well: + +```toml +[[datasets]] +image_directory = "targets" +reference_directory = "references" +reference_cache_directory = "cache_ref" +``` + +For multi-reference `av_ic`, use the plural dataset keys instead: + +```toml +[[datasets]] +video_directory = "videos" +reference_directories = ["references_a", "references_b"] +reference_cache_directories = ["cache_ref_a", "cache_ref_b"] +reference_audio_directories = ["reference_audio_a", "reference_audio_b"] +reference_audio_cache_directories = ["cache_ref_audio_a", "cache_ref_audio_b"] +target_frames = [33] +``` + +In the dashboard, these map to the Advanced dataset fields: +- `Reference Cache Dir` + `Extra Ref Cache Dirs` +- `Reference Directory` + `Extra Reference Dirs` +- `Ref Audio Cache Dir` + `Extra Ref Audio Cache Dirs` +- `Ref Audio Directory` + `Extra Ref Audio Dirs` + +In the training dashboard, AV IC behavior is configured from the Advanced LoRA section: +- `IC-LoRA Strategy = av_ic` +- `AV Cross-Attn` for `both` / `a2v_only` / `v2a_only` / `none` +- `Multi-Ref AV` when the dataset uses the plural reference directory fields above + +##### Step 3: Cache Latents + +Cache both video latents and reference latents in one step: + +```bash +python ltx2_cache_latents.py ^ + --dataset_config dataset.toml ^ + --ltx2_checkpoint /path/to/ltx-2.safetensors ^ + --device cuda ^ + --vae_dtype bf16 +``` + +Reference latents are automatically cached to `reference_cache_directory` when `reference_directory` is configured. + +**Downscaled references** (`--reference_downscale`): +```bash +python ltx2_cache_latents.py ^ + --dataset_config dataset.toml ^ + --ltx2_checkpoint /path/to/ltx-2.safetensors ^ + --reference_downscale 2 ^ + --device cuda +``` + +`--reference_downscale 2` encodes references at half spatial resolution (e.g., 384px for 768px target). Position embeddings on the reference spatial axes are scaled by the factor so they map into the target coordinate space. When downscaling is enabled, LTX2 buckets are aligned to `32 * reference_downscale` pixels so cached reference dimensions remain exact `/32` latent-grid multiples instead of being rounded down. + +##### Step 4: Cache Text Encoder Outputs + +Same as standard training — no special flags needed: +```bash +python ltx2_cache_text_encoder_outputs.py ^ + --dataset_config dataset.toml ^ + --ltx2_checkpoint /path/to/ltx-2.safetensors ^ + --gemma_root /path/to/gemma ^ + --gemma_load_in_8bit ^ + --device cuda +``` + +##### Step 5: Train + +Use `--lora_target_preset v2v` (targets attention + FFN layers): + +```bash +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 ltx2_train_network.py ^ + --mixed_precision bf16 ^ + --dataset_config dataset.toml ^ + --ltx2_checkpoint /path/to/ltx-2.safetensors ^ + --fp8_base --fp8_scaled ^ + --blocks_to_swap 10 ^ + --sdpa ^ + --gradient_checkpointing ^ + --network_module networks.lora_ltx2 ^ + --network_dim 32 --network_alpha 32 ^ + --lora_target_preset v2v ^ + --ltx2_first_frame_conditioning_p 0.2 ^ + --timestep_sampling shifted_logit_normal ^ + --learning_rate 1e-4 ^ + --sample_at_first ^ + --sample_every_n_epochs 5 ^ + --sample_prompts sampling_prompts.txt ^ + --sample_include_reference ^ + --output_dir output ^ + --output_name ltx2_ic_lora +``` + +If you used `--reference_downscale` during caching, also pass it during training: +```bash + --reference_downscale 2 +``` + +##### Step 6: Sample Prompts + +Append `--v ` after the prompt text in your sampling prompts file to specify the V2V reference for each prompt. Both images and videos are supported: + +``` +A woman walking through a forest --v references/scene_001.png --n blurry, low quality +A cat sitting on a windowsill --v references/scene_002.mp4 --n distorted +``` + +The `--sample_include_reference` flag shows the reference side-by-side with the generated output in validation videos. + +##### IC-LoRA Arguments + +| Argument | Default | Description | +|----------|---------|-------------| +| `--reference_downscale` | 1 | Spatial downscale factor for references (1=same res, 2=half) | +| `--reference_frames` | 1 | Number of reference frames for V2V (images are repeated to fill this count) | +| `--ltx2_first_frame_conditioning_p` | 0.1 | Probability of also conditioning on the first target frame during training. No effect for single-frame (image) samples | +| `--sample_include_reference` | off | Show reference side-by-side with generated output in sample videos | +| `--lora_target_preset v2v` | — | Targets attention + FFN layers (recommended for IC-LoRA) | + +##### Dataset Config Options + +| Option | Type | Description | +|--------|------|-------------| +| `reference_directory` | string | Path to reference images/videos for IC-LoRA datasets (matched by filename stem) | +| `reference_directories` | array[string] | Optional multi-reference variant of `reference_directory`; use one entry per reference stream | +| `reference_cache_directory` | string | Output directory for cached reference latents | +| `reference_cache_directories` | array[string] | Optional multi-reference variant of `reference_cache_directory`; count must match `reference_directories` | +| `reference_frames` | int | Optional per-dataset override for `--reference_frames` during reference latent caching | + +##### Notes + +- **First-frame conditioning** (`--ltx2_first_frame_conditioning_p`): Randomly conditions on the first target frame in addition to the reference. Only applied during training; inference always denoises the full target. Has no effect for single-frame (image-only) samples — the code skips conditioning when `num_frames == 1` since there are no subsequent frames to generate. +- **Multi-frame references**: Supported but increase VRAM usage proportionally to the number of reference tokens. +- **Multi-reference datasets**: `av_ic` can consume multiple references directly from dataset TOML via `reference_directories` + `reference_cache_directories` (and the audio equivalents below). The list lengths must match. `--av_multi_ref` exposes that intent in training metadata/UI. +- **Multi-subject references**: The VAE compresses 8 frames into 1 temporal latent via `SpaceToDepthDownsample`, which pairs consecutive frames and averages their features. Subjects sharing the same 8-frame group are blended and lose individual identity. To keep N subjects separated, structure your reference video as: frame 1 = Subject A, frames 2–9 = Subject B (repeated 8×), frames 10–17 = Subject C (repeated 8×), etc. Total frames: `1 + 8×(N−1)`. Set `--reference_frames` to match. Frame 1 gets its own latent due to causal padding in the encoder; each subsequent 8-frame block produces one additional latent. +- **Video-only**: IC-LoRA requires `--ltx2_mode video`. Audio-video mode is not supported for v2v training. +- **Downscale factor metadata**: Saved in LoRA safetensors as `ss_reference_downscale_factor` when factor != 1. +- **Two-stage inference**: Not supported with V2V; a warning is emitted and the reference is ignored. + +#### Audio-Reference IC-LoRA + +> This approach is based on [ID-LoRA](https://github.com/ID-LoRA/ID-LoRA), adapted for audio-video conditioning in the LTX-2 transformer. + +Trains a LoRA using in-context audio-reference conditioning. Reference audio latents (clean, timestep=0) are concatenated with noisy target audio latents during training. Loss is computed only on the target portion. In AV mode the LoRA targets audio self/cross-attention, audio FFN, and bidirectional audio-video cross-modal attention layers; in audio-only mode the `audio` preset is auto-selected, which omits cross-modal layers that connect to the (dummy) video branch. + +Supported modes: +- **`--ltx2_mode av`** — full audio-video model; trains both video and audio IC-LoRA layers. +- **`--ltx2_mode audio`** — audio-only mode; trains only audio layers (video is a dummy zero tensor). `--lora_target_preset audio` is auto-selected (cross-modal layers that affect the dummy video branch are omitted). + +##### Recommended settings + +The ID-LoRA reference configuration uses the following settings. The trainer warns when the main audio-reference separation flags are off, and warns about first-frame conditioning only when it is effectively disabled in AV mode. + +| Setting | Recommended value | Why | +|---------|-------------------|-----| +| `--ltx2_first_frame_conditioning_p` | `0.9` | Face identity comes from the first frame; voice identity comes from the reference LoRA. Without this, face identity is uncontrolled. | +| `--audio_ref_use_negative_positions` | enabled | Clean positional separation between reference and target in RoPE space. | +| `--audio_ref_mask_cross_attention_to_reference` | enabled | Forces video to sync with target audio only (not reference). AV mode only. | +| `--audio_ref_mask_reference_from_text_attention` | enabled | Prevents reference audio from attending to text describing the target speech. | +| `--timestep_sampling` | `shifted_logit_normal` | Timestep distribution used by ID-LoRA. | +| `--network_dim` / `--network_alpha` | `128` / `128` | LoRA rank used by ID-LoRA. | + +> **Inference note**: Attention masks (`--audio_ref_mask_cross_attention_to_reference` and `--audio_ref_mask_reference_from_text_attention`) are **training scaffolding only**. They are automatically disabled during sampling/inference, matching the ID-LoRA reference which explicitly turns masks off at validation time. The masks force the model to learn proper attention patterns during training; at inference time the LoRA weights have already internalized the separation, so masks are unnecessary. + +##### How it works + +1. Reference audio is encoded to latents and concatenated with noisy target audio along the temporal axis. +2. Reference tokens receive timestep=0 (no noise); target tokens receive the sampled sigma. +3. Loss is masked to exclude the reference portion — the model only learns to predict the target. +4. Three optional attention overrides control how the reference interacts with the rest of the model: + - **Negative positions**: shifts reference tokens into negative RoPE time, creating clean positional separation from target tokens. + - **A2V cross-attention mask**: blocks video from attending to reference audio (video syncs with target audio only). + - **Text attention mask**: blocks reference audio from attending to text (reference provides identity, not content). + +##### Step 1: Prepare Data + +Organize training videos with matching reference audio files (same filename stem): + +``` +videos/ reference_audio/ + speaker_001.mp4 speaker_001.wav # reference clip for speaker_001 + speaker_002.mp4 speaker_002.flac +``` + +Reference audio files are matched to training videos by filename stem. + +##### Step 2: Dataset Config + +```toml +[general] +resolution = [768, 512] +caption_extension = ".txt" +batch_size = 1 +enable_bucket = true +cache_directory = "cache" +reference_audio_cache_directory = "cache_ref_audio" +separate_audio_buckets = true + +[[datasets]] +video_directory = "videos" +reference_audio_directory = "reference_audio" +target_frames = [1, 17, 33] +``` + +##### Step 3: Cache Latents + +```bash +python ltx2_cache_latents.py ^ + --dataset_config dataset.toml ^ + --ltx2_checkpoint /path/to/ltxav-2.safetensors ^ + --ltx2_mode av ^ + --device cuda ^ + --vae_dtype bf16 +``` + +For audio-only mode, replace `--ltx2_mode av` with `--ltx2_mode audio` (no video latents are cached, only audio and reference audio latents). + +Reference audio latents are automatically cached to `reference_audio_cache_directory`. + +##### Step 4: Cache Text Encoder Outputs + +No special flags — use whichever mode you are training: + +```bash +python ltx2_cache_text_encoder_outputs.py ^ + --dataset_config dataset.toml ^ + --ltx2_checkpoint /path/to/ltxav-2.safetensors ^ + --ltx2_mode av ^ + --gemma_root /path/to/gemma ^ + --gemma_load_in_8bit ^ + --device cuda +``` + +For audio-only mode, replace `--ltx2_mode av` with `--ltx2_mode audio`. + +##### Step 5: Train + +```bash +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 ltx2_train_network.py ^ + --mixed_precision bf16 ^ + --dataset_config dataset.toml ^ + --ltx2_checkpoint /path/to/ltxav-2.safetensors ^ + --ltx2_mode av ^ + --fp8_base --fp8_scaled ^ + --blocks_to_swap 10 ^ + --sdpa ^ + --gradient_checkpointing ^ + --network_module networks.lora_ltx2 ^ + --network_dim 128 --network_alpha 128 ^ + --lora_target_preset audio_ref_ic ^ + --audio_ref_use_negative_positions ^ + --audio_ref_mask_cross_attention_to_reference ^ + --audio_ref_mask_reference_from_text_attention ^ + --ltx2_first_frame_conditioning_p 0.9 ^ + --timestep_sampling shifted_logit_normal ^ + --learning_rate 2e-4 ^ + --sample_at_first ^ + --sample_every_n_epochs 5 ^ + --sample_prompts sampling_prompts.txt ^ + --output_dir output ^ + --output_name ltx2_audio_ref_ic_lora +``` + +**Audio-only mode** — replace `--ltx2_mode av` with `--ltx2_mode audio` and omit `--lora_target_preset` (auto-selected as `audio`): + +```bash +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 ltx2_train_network.py ^ + --mixed_precision bf16 ^ + --dataset_config dataset.toml ^ + --ltx2_checkpoint /path/to/ltxav-2.safetensors ^ + --ltx2_mode audio ^ + --ic_lora_strategy audio_ref_ic ^ + --fp8_base --fp8_scaled ^ + --blocks_to_swap 10 ^ + --sdpa ^ + --gradient_checkpointing ^ + --network_module networks.lora_ltx2 ^ + --network_dim 128 --network_alpha 128 ^ + --audio_ref_use_negative_positions ^ + --audio_ref_mask_reference_from_text_attention ^ + --timestep_sampling shifted_logit_normal ^ + --learning_rate 2e-4 ^ + --sample_at_first ^ + --sample_every_n_epochs 5 ^ + --sample_prompts sampling_prompts.txt ^ + --output_dir output ^ + --output_name ltx2_audio_ref_ic_lora_audioonly +``` + +##### Step 6: Sample Prompts + +Use `--ra ` in your sampling prompts file to specify the reference audio: + +``` +--ra reference_audio/speaker_001.wav A person speaking about nature --n blurry, low quality +--ra reference_audio/speaker_002.flac A woman laughing in a park +``` + +Reference audio latents are precached automatically when using `--precache_sample_latents` during latent caching. + +##### Audio-Reference IC-LoRA Arguments + +| Argument | Default | Description | +|----------|---------|-------------| +| `--ic_lora_strategy audio_ref_ic` | auto | Activates audio-reference IC-LoRA mode (auto-inferred from `--lora_target_preset audio_ref_ic`) | +| `--lora_target_preset audio_ref_ic` | — | Targets audio attn/FFN + bidirectional AV cross-modal layers | +| `--audio_ref_use_negative_positions` | off | Place reference audio in negative RoPE time for positional separation | +| `--audio_ref_mask_cross_attention_to_reference` | off | Block video from attending to reference audio tokens (AV mode only; no effect in audio-only mode) | +| `--audio_ref_mask_reference_from_text_attention` | off | Block reference audio from attending to text tokens (`av_ic`: currently unsupported and ignored) | +| `--audio_ref_identity_guidance_scale` | 0.0 | Override CFG scale for target-audio branch during `audio_ref_ic` sampling (0 = use standard guidance scale) | + +##### Dataset Config Options + +| Option | Type | Description | +|--------|------|-------------| +| `reference_audio_directory` | string | Path to reference audio files (matched by filename stem) | +| `reference_audio_directories` | array[string] | Optional multi-reference variant of `reference_audio_directory`; use one entry per reference stream | +| `reference_audio_cache_directory` | string | Output directory for cached reference audio latents | +| `reference_audio_cache_directories` | array[string] | Optional multi-reference variant of `reference_audio_cache_directory`; count must match `reference_audio_directories` | + +##### Notes + +- **Checkpoint**: requires an LTXAV checkpoint for both `--ltx2_mode av` and `--ltx2_mode audio`. +- **Bucket separation**: `separate_audio_buckets = true` keeps audio/non-audio items in separate batches (avoids shape mismatches in collation). +- **Attention masks are training-only**: `--audio_ref_mask_cross_attention_to_reference` and `--audio_ref_mask_reference_from_text_attention` are applied only during training. They are automatically disabled during sampling/inference to match the ID-LoRA reference (which explicitly sets both to `false` during validation). Negative position overrides are always applied. +- **`av_ic` limitation**: `--audio_ref_mask_reference_from_text_attention` is not currently supported in `av_ic` because the Modality API uses a 2D `context_mask`; the trainer warns and ignores this flag. +- **AV cross-attention modes**: `--av_cross_attention_mode both` is the default `av_ic` behavior. Use `a2v_only` for audio-to-video only, `v2a_only` for video-to-audio only, or `none` to disable AV cross-modal attention while keeping the rest of `av_ic` intact. All require `--ltx2_mode av`. +- **Multi-reference `av_ic`**: accepts multiple reference latents when they are provided as stacked tensors or extra `ref_*` entries, and concatenates them before conditioning. This keeps the implementation compatible with the existing single-reference path while allowing richer identity/style aggregation. `--av_multi_ref` is the explicit training-side toggle for this setup. +- **`video_ref_only_av`**: requires `--ltx2_mode av`, uses reference video only, and keeps the audio branch target-only. This is useful when you want identity/motion conditioning from video without requiring reference audio for every sample. +- **First-frame conditioning**: for identity-sensitive AV IC-LoRA, `--ltx2_first_frame_conditioning_p 0.9` is the documented starting point. Without it, identity transfer from the target first frame is often weak. A warning is emitted if this is not set in AV mode. +- `--ic_lora_strategy auto` (default) infers the strategy from `--lora_target_preset` via `infer_ic_lora_strategy_from_preset()`. + +#### Latent Guides + +Latent guides inject a per-sample reference latent directly into the video token stream — orthogonal to the IC-LoRA reference-video pathway. They are loaded from dataset directories (one stem-matched image per video sample), VAE-encoded once during latent caching, and applied automatically at training and inference time. + +Two kinds, mirroring upstream Lightricks `VideoConditionByLatentIndex` / `VideoConditionByKeyframeIndex`: + +- **`latent_idx`** — *token replacement* at a fixed frame slot. The guide latent overwrites tokens at `frame_idx` (and the loss is masked there, so the model only learns to denoise the remaining frames). `frame_idx=0` reproduces standard I2V conditioning; non-zero indices anchor a frame mid-video. Loss/timestep parity is preserved by re-masking the affected tokens as clean (`t=0`) per-token. +- **`keyframe`** — *token append* with custom positional encoding. A patchified keyframe latent is concatenated to the video token sequence. Positions are offset by `frame_idx` then divided by `frame_rate`. `frame_idx=-1` yields slightly-negative timestamps (the global-reference convention from upstream), making the keyframe visible to every output frame without claiming a specific slot. Predictions for the appended tokens are sliced off before loss. + + Strength is plumbed via per-token `denoise_mask = 1 - strength`, matching upstream `VideoConditionByKeyframeIndex`. The appended tokens get effective timestep `denoise_mask × sigma`: at `strength=1.0` this is `t=0` (clean conditioning); at `strength=0.0` this is `t=sigma` (the model sees the keyframe as pure noise, so it contributes no information). For scalar (per-batch) strength the latent itself is never modified — strength only modulates how "clean" the model perceives the keyframe to be. Per-sample strength tensors (used by Endpoint Keyframe Training) are an exception: when some samples in the batch have `strength<=0`, those samples' guide latent is replaced with `randn` noise before patchifying, to prevent leaking clean target-derived content into a fully-noisy mask slot. + +Both can be set independently and per-dataset. + +##### Dataset Config Options + +| Option | Type | Default | Description | +|---|---|---|---| +| `latent_idx_guide_directory` | string | — | Stem-matched guide images. Activates `latent_idx` for this dataset. | +| `latent_idx_guide_cache_directory` | string | — | Required when the source directory is set. | +| `latent_idx_guide_frame_idx` | int | `0` | Slot to replace. Training raises `ValueError` if `frame_idx < 0` or `frame_idx + T_guide > num_frames`. | +| `latent_idx_guide_strength` | float | `1.0` | Training requires exactly `1.0` and raises `ValueError` otherwise (out-of-range values are clamped to `[0, 1]` with a warning before the check fires). Inference accepts any value via the 5D `denoise_mask = 1 - strength`. | +| `keyframe_guide_directory` | string | — | Stem-matched global-reference images. Activates `keyframe`. | +| `keyframe_guide_cache_directory` | string | — | Required when the source directory is set. | +| `keyframe_guide_frame_idx` | int | `-1` | **Pixel-frame** index (NOT latent-frame). `-1` = global reference (slightly-negative timestamps, visible to all frames). For non-negative values, multiply the desired latent-frame by `VIDEO_SCALE_FACTORS.time` first — for LTX-2 (8× temporal VAE), latent frame `L` corresponds to `frame_idx = L × 8`. Example: anchor at the last latent frame of a 9-latent-frame video → `frame_idx = 64`. | +| `keyframe_guide_strength` | float | `1.0` | Per-token `denoise_mask = 1 - strength` → effective appended timestep = `(1-strength) × sigma`. `1.0` = clean conditioning; `0.0` = full noise / no contribution. Clamped to `[0, 1]`. | +| `keyframe_guide_extra_directories` | array[string] | — | Optional. Stack additional keyframes beyond the primary. | +| `keyframe_guide_extra_cache_directories` | array[string] | — | Cache directories for the extras (parallel to the directories list). | +| `keyframe_guide_extra_frame_idxs` | array[int] | — | Per-extra `frame_idx` values. | +| `keyframe_guide_extra_strengths` | array[float] | — | Per-extra `strength` values. | + +The four `keyframe_guide_extra_*` arrays must all have the same length. The primary keyframe (above) must also be set. + +`strength` semantics differ between guide types and are NOT interchangeable: + +- **`latent_idx_guide_strength`** is a **replacement-lock strength**. The guide latent overwrites tokens at the slot in-place; `strength` controls the per-token `denoise_mask` for those tokens. Training requires exactly `1.0` (hard lock); only inference supports continuous `<1.0`. +- **`keyframe_guide_strength`** is an **append-guide strength**. The guide latent is appended as a new token block at the configured `frame_idx`; the original target tokens are still denoised normally. `strength` controls the appended block's `denoise_mask` (`1.0` = clean conditioning, `0.0` = effectively absent and the guide is dropped). Continuous values are accepted at both training and inference. + +If you want frame N pixels to *exactly* match a reference image, use `latent_idx`. If you want the model to be *guided toward* a reference, use `keyframe`. + +Example multi-keyframe TOML: +```toml +keyframe_guide_directory = "/data/identity" +keyframe_guide_cache_directory = "/cache/identity" +keyframe_guide_frame_idx = -1 +keyframe_guide_extra_directories = ["/data/style"] +keyframe_guide_extra_cache_directories = ["/cache/style"] +keyframe_guide_extra_frame_idxs = [5] +keyframe_guide_extra_strengths = [0.7] +``` + +`ltx2_cache_latents.py` auto-encodes any guide directory it finds in the dataset config — no new CLI flags. Items differing in any guide-config detail (presence, count, `frame_idx`, `strength`) land in separate buckets, so each batch is shape-uniform. + +##### IC-LoRA Compatibility Matrix + +| `--ic_lora_strategy` | `--ltx2_mode` | `latent_idx` | `keyframe` | +|---|---|---|---| +| `none` | `video` / `av` | ✓ | ✓ | +| `v2v` | `video` | ✓ | ✓ | +| `av_ic` | `av` | ✓ | ✓ | +| `video_ref_only_av` | `av` | ✓ | ✓ | +| `audio_ref_ic` | `av` | ✓ | ✓ | +| `audio_ref_ic` | `audio` | n/a (no video target) | n/a | + +`latent_idx` overwrites the noisy-target tensor before patchify, so it works on every branch that produces video tokens. `keyframe` token-append is wired through the `LTX2Wrapper.forward` path for the simple/audio-ref-only paths and via `build_keyframe_extension` for the v2v / av_ic / video_ref_only_av IC-LoRA branches; in all cases the appended timesteps are `(1 − strength) × sigma` and the predictions are sliced off before loss. + +Notes on edge cases: +- **`reference_downscale_factor`** (set on the dataset for v2v / av_ic / video_ref_only_av when ref-video resolution is lower than the target) is propagated into keyframe positions inside `build_keyframe_extension` so a downscaled keyframe carries spatial positions consistent with the ref-video. The simple path runs at full resolution and ignores this factor. +- **Inference image-resize on shape mismatch**: in `ltx2_inference.py:_denoise_loop`, both latent_idx and keyframe guide latents are bilinearly resized to the current denoising stage's spatial resolution if they don't already match (relevant for `--sample_two_stage` where stage 1 runs at half-resolution). +- **`--sample_i2v_token_timestep_mask`**: when set (default), inference only zeroes the token timestep at locked slots when `strength == 1.0`. With `strength < 1.0`, the per-token timestep follows `(1 − strength) × sigma` and the boolean mask is not applied. +- **Single-stage and two-stage sampling** both consume guides during sample-prompt previews. + +##### Endpoint Keyframe Training + +Optional training-time CLI flags that extract first / last / random-interior latent frames of the target video and append them as clean keyframe tokens, without requiring per-item keyframe images on disk. Composes with any `--ic_lora_strategy` (the endpoint guides are appended to the same `keyframe_guides_for_options` list that external keyframes use). + +| Flag | Default | Description | +|---|---|---| +| `--keyframe_endpoint_training` | off | Master enable. All flags below are no-ops when this is unset. | +| `--keyframe_first_frame_p` | `1.0` | Per-sample probability of appending the first latent frame as a clean keyframe at `frame_idx=0` (independent Bernoulli per item in the batch). | +| `--keyframe_last_frame_p` | `1.0` | Per-sample probability of appending the last latent frame at `frame_idx=(T−1) × VIDEO_SCALE_FACTORS.time` (pixel-frame units; for LTX-2's 8× temporal VAE this is `(T−1) × 8`). | +| `--keyframe_random_interior_p` | `0.0` | Per-sample probability of appending random interior latent frames as keyframes. Interior indices are shared across the batch; only the dropout decision is per-sample. | +| `--keyframe_max_random_interior` | `0` | Maximum number of random interior latent frames to append per batch when any sample triggers. Sampled without replacement from `[1, T−2]`, sorted ascending. | + +When the master flag is on, each per-frame probability is sampled independently **per sample** within the batch (Bernoulli; `1.0` always fires, `0.0` never fires). Within one batch, some samples may receive a given endpoint guide while others do not — the guide is appended uniformly (required for tensor packing) but the per-sample denoise_mask is `0` (clean) for samples that won the flip and `1` (no effect) for those that didn't. For losers (samples that did not win the flip), the appended guide latent is replaced with random noise *before* patchifying, so the model sees noise tokens with `denoise_mask=1` rather than clean target-derived content tagged as fully noisy — this prevents a leak of the supervision target through the appended-token stream. Endpoint guides stack with any external keyframes from `keyframe_guide_directory` (external first, endpoints appended after). + +Example: train an interpolation LoRA from raw videos, both endpoints always present, no interior augmentation: +``` +--keyframe_endpoint_training \ +--keyframe_first_frame_p 1.0 \ +--keyframe_last_frame_p 1.0 +``` + +Example: same but with up to 2 random interior keyframes 30% of the time, for a model that learns to use keyframes at arbitrary positions: +``` +--keyframe_endpoint_training \ +--keyframe_random_interior_p 0.3 \ +--keyframe_max_random_interior 2 +``` + +Caveats and tradeoffs: + +- **Distribution match**: endpoint keyframes are sliced directly from the encoded video latent, not from a separately VAE-encoded still image. The first latent frame of LTX-2's 8× causal VAE encodes essentially pixel-frame 0 (causal_fix anchors it), so first-frame extraction is close to a still-image encode. The last and interior latent slices represent ~8 pixel-frames each of motion context, so they carry temporal information a single still image would not. To match the inference distribution exactly when keyframes will come from images at sample time, prefer the dataset-driven `keyframe_guide_directory` workflow with images that are encoded individually via the same VAE, OR train on still-image-derived latents and use endpoint extraction only as augmentation. +- **Soft conditioning, not hard locks**: keyframes are appended tokens with `denoise_mask = 1 - strength`. The original target latent at the corresponding frame is still denoised normally. The model learns to be guided by the keyframe; it does not have a hard constraint to reproduce it pixel-exact. For exact endpoint preservation (image-to-video with frame 0 fixed), use a `latent_idx` guide (token replacement at that slot) instead of (or in addition to) keyframe append. +- **Distribution under defaults**: defaults `first_p=1.0, last_p=1.0, interior_p=0.0` train two-ended interpolation. Single-anchor i2v (set `last_p=0`) and last-anchor extension (set `first_p=0`) are out-of-distribution unless you train with those probabilities directly. +- **`strength=0` keyframes are skipped entirely** (they would otherwise add tokens to attention with no useful signal). At inference, this means a `--gk` guide with `:0.0` is equivalent to omitting it. + +##### Video Anchor Training + +Optional training-time augmentation for workflows that use clean video frames as anchors. During some training samples, selected target frames are kept as known frames while the model trains on the rest of the video. + +| Flag | Default | Description | +|---|---|---| +| `--video_anchor_training` | off | Master enable. When unset, generated commands do not include the video-anchor flags. | +| `--video_anchor_probability` | `0.5` | Per-sample probability of applying video-anchor training. | +| `--video_anchor_count` | `1` | Number of random anchors to add per sample when the strategy includes random anchors. | +| `--video_anchor_strategy` | `endpoints_random` | `endpoints` keeps first/last frames only, `random` samples anchors uniformly, and `endpoints_random` combines both. | + +Use this only when your target workflow benefits from anchor-like conditioning, such as first/last-frame control, video-to-video refinement, reference-guided training, or experiments where the model should see fixed in-clip frames while learning the surrounding motion. It is not a general quality switch for every run. + +Suggested starting point: +``` +--video_anchor_training \ +--video_anchor_probability 0.25 \ +--video_anchor_count 1 \ +--video_anchor_strategy endpoints_random +``` + +Caveats and tradeoffs: + +- **Video target required**: `--video_anchor_training` is rejected for `--ltx2_mode audio` and audio-only checkpoints because there are no video target latents to anchor. +- **Random strategy needs anchors**: `--video_anchor_strategy random` requires `--video_anchor_count >= 1`; use `endpoints` if you only want first/last-frame anchors. +- **No inference behavior is added**: this is training-only. +- **No guaranteed quality gain**: evaluate against your target prompts and sampling workflow before using it as a default. + +##### Sample Prompt Flags + +| Flag | Meaning | +|---|---| +| `--gl frame_idx:path[:strength]` | `latent_idx` guide for this prompt. Multiple allowed. | +| `--gk frame_idx:path[:strength]` | `keyframe` guide for this prompt. Multiple allowed. | + +Guides take effect on both single-stage and two-stage sampling paths. + +#### Sampling with Tiled VAE + +The prompt file format (`--sample_prompts`) — including guidance scale, negative prompt, and per-prompt inference parameters — is documented in the [Sampling During Training guide](./sampling_during_training.md). LTX-2 extends this with `--v ` (IC-LoRA reference) and `--ra ` (audio-reference IC-LoRA) prompt-line options. Put these options after the prompt text. + +| Argument | Default | Description | +|----------|---------|-------------| +| `--height` | 512 | Base sample output height. With the default sampling preset, LTX-2.3 uses `512` unless the prompt line sets `--h` | +| `--width` | 768 | Base sample output width. With the default sampling preset, LTX-2.3 uses `768` unless the prompt line sets `--w` | +| `--sample_num_frames` | 45 | Base sample frame count. With the default sampling preset, LTX-2.3 uses `121` unless the prompt line sets `--f` | +| `--sample_with_offloading` | off | Offload DiT to CPU between sampling prompts to save VRAM | +| `--sample_tiled_vae` | off | Enable tiled VAE decoding during sampling to reduce VRAM | +| `--sample_vae_tile_size` | 512 | Spatial tile size (pixels) | +| `--sample_vae_tile_overlap` | 64 | Spatial tile overlap (pixels) | +| `--sample_vae_temporal_tile_size` | 0 | Temporal tile size in frames (0 = disabled) | +| `--sample_vae_temporal_tile_overlap` | 8 | Temporal tile overlap (frames) | +| `--sample_merge_audio` | off | Merge generated audio into the output `.mp4` | +| `--sample_audio_only` | off | Generate audio-only preview outputs | +| `--sample_disable_audio` | off | Disable audio preview generation during sampling | +| `--sample_audio_subprocess` | on | Decode audio in a subprocess to avoid OOM crashes. Use `--no-sample_audio_subprocess` to decode in-process | +| `--sample_disable_flash_attn` | off | Force SDPA instead of FlashAttention during sampling | +| `--sample_i2v_token_timestep_mask` | on | Use I2V token timestep masking (conditioned tokens use t=0). Use `--no-sample_i2v_token_timestep_mask` to disable | +| `--sample_sampling_preset` | `defaults` | Validation sampling preset. For `--ltx_version 2.3`, this resolves to the LTX-2.3 defaults (`30` steps, `768x512`, `121` frames, CFG/STG defaults, CFG rescale `0.7`). Use `legacy` only to bypass preset defaults | +| `--sample_sampler` | `auto` | Denoising sampler. `auto` uses `res_2s` for full LTX presets and Euler for `distilled_two_stage` | +| `--sample_sigma_schedule` | `auto` | Sigma schedule. `auto` uses latent-aware LTX shifted sigmas and the exact LTX-2.3 distilled schedule for the distilled preset | + +#### Precached Sample Prompts +To avoid loading Gemma during training for sample generation, you can precache the prompt embeddings: + +1. During text encoder caching, add `--precache_sample_prompts --sample_prompts sampling_prompts.txt` to also cache the sample prompt embeddings. +2. During training, add `--use_precached_sample_prompts` (or `--precache_sample_prompts`) to load embeddings from cache instead of running Gemma. +- `--sample_prompts_cache`: Path to the precached embeddings file. Defaults to `/ltx2_sample_prompts_cache.pt`. + +For IC-LoRA / V2V training, you can also precache the conditioning image latents during latent caching (see [Latent Caching Arguments](#latent-caching-arguments)): +1. During latent caching, add `--precache_sample_latents --sample_prompts sampling_prompts.txt`. +2. During training, add `--use_precached_sample_latents` to load conditioning latents from cache instead of loading the VAE encoder. +- `--sample_latents_cache`: Path to the precached latents file. Defaults to `/ltx2_sample_latents_cache.pt`. +- Rebuild this cache after changing sample prompt `--w`, `--h`, or `--reference_downscale`; cached video conditioning latent shapes are validated and stale spatial shapes are rejected. Rebuild manually after changing `--i` or `--v`, because cache entries are matched by prompt index rather than by source path. + +#### Two-Stage Sampling + +> [!NOTE] +> This feature is disabled by default. Two-stage inference generates at half resolution, then upsamples and refines. It is intended for larger final outputs; at `512x512`, stage 1 is only `256x256`, so compare against the single-stage baseline before using it. + +| Argument | Default | Description | +|----------|---------|-------------| +| `--sample_two_stage` | off | Enable two-stage inference during sampling | +| `--spatial_upsampler_path` | — | Path to spatial upsampler model. Required when `--sample_two_stage` is set | +| `--distilled_lora_path` | — | Path to distilled LoRA for stage refinement. External-format LTX-2 LoRAs are converted automatically | +| `--sample_stage2_steps` | 3 | Number of denoising steps for stage 2 | +| `--sample_stage1_distilled_lora_multiplier` | auto | Optional stage-1 distilled LoRA strength. With `res_2s`, auto uses `0.25`; with Euler, auto uses `0.0` | +| `--sample_stage2_distilled_lora_multiplier` | auto | Optional stage-2 distilled LoRA strength. With `res_2s`, auto uses `0.5`; with Euler, auto uses `1.0` | + +LTX-2.3 preview starting point: + +```bash +--sample_sampling_preset ltx23 ^ +--sample_sampler auto ^ +--sample_sigma_schedule auto +``` + +Prompt-level `--w`, `--h`, `--f`, and `--s` values override preset defaults. For LTX-2.3 presets, explicit `--w`/`--h` values with a short side below `544` or an aspect ratio outside the near-16:9/9:16 warning range, and explicit `--s` values different from the preset step count, are logged as warnings. + +#### Checkpoint Output Format + +Saved LoRA checkpoints are converted to ComfyUI format by default. Both the original musubi-tuner format and the ComfyUI format are kept. For the standalone conversion utility, see `convert_lora.py`. + +| Flag | Behavior | +|------|----------| +| *(default)* | Saves both `*.safetensors` (original) and `*.comfy.safetensors` (ComfyUI). | +| `--no_save_original_lora` | Deletes the original after conversion, keeping only `*.comfy.safetensors`. | +| `--no_convert_to_comfy` | Saves only the original `*.safetensors` (no conversion). | +| `--save_checkpoint_metadata` | Saves a `.json` sidecar file alongside each checkpoint with loss, lr, step, and epoch. | + +> **Important:** Training can only be resumed from the **original** (non-comfy) checkpoint format. If you plan to use `--resume`, do not use `--no_save_original_lora`. +> ComfyUI-only LoRA files can still be used for warm-starting via `--network_weights`, `--base_weights`, or `--dim_from_weights`; only full `--resume` requires the original checkpoint plus saved training state. + +For DoRA LoRA and DokR LoKr, keep the original `*.safetensors` file for Musubi loading and resume. The training-time ComfyUI export is intended for ComfyUI and stores `dora_scale`; converting that file back to native Musubi DoRA/DokR requires base-weight information that is not present in the standalone ComfyUI checkpoint. + +Checkpoint rotation (`--save_last_n_epochs`) cleans up old ComfyUI checkpoints alongside originals. HuggingFace upload (`--huggingface_repo_id`) uploads both formats by default. Use `--no_save_original_lora` to upload only the ComfyUI checkpoint. + +#### Resuming Training + +Requires `--save_state` to be enabled. State directories contain optimizer, scheduler, and RNG states. See the [Advanced Configuration guide](./advanced_config.md) for general `--save_state` / `--resume` behavior shared across all architectures. + +| Flag | Description | +|------|-------------| +| `--resume ` | Resume from a specific state directory | +| `--autoresume` | Automatically resume from the latest state in `output_dir`. Ignored if `--resume` is specified. Starts from scratch if no state is found | +| `--reset_optimizer` | Clear optimizer momentum/variance on resume, keep model weights only | +| `--reset_optimizer_params` | Reset optimizer param groups (lr, weight_decay, etc.) to current CLI values on resume, keep momentum/variance | +| `--reset_dataloader` | Skip mid-epoch batch skip, restart epoch from beginning | + +**Changing learning rate on resume:** When you resume from a saved state, the optimizer's learning rate is restored from the checkpoint — any new `--learning_rate` value on the command line is silently ignored. To apply a new learning rate, add `--reset_optimizer_params`. This resets lr, weight_decay, and other optimizer param-group settings to your current CLI values while keeping the accumulated momentum/variance intact. + +Mid-epoch checkpoints record `step_in_epoch` in `resume_metadata.json`. On resume, already-processed batches are skipped to keep global step consistent. `--reset_dataloader` disables this. + +The moving average loss is saved in state checkpoints and restored on resume. + +Newly saved state directories also include `state_manifest.json`, written only after the accelerator state save completes. `--autoresume` and the dashboard resume detector ignore incomplete state directories, so a crashed or force-killed save is not selected accidentally. + +When training is launched from the dashboard, pressing Stop first requests a graceful interrupt save. The trainer writes an `*-interrupt-step########-state` directory with resume metadata, then exits. Pressing Stop again while the process is already stopping requests a force stop and skips the interrupt save. + +--- + +## Merge LoRA into Base Model + +**Script:** `ltx2_merge_lora_to_model.py` + +```bash +python ltx2_merge_lora_to_model.py ^ + --dit base_model.safetensors ^ + --lora_weight lora.safetensors ^ + --save_merged_model merged_model.safetensors +``` + +### Merge-to-Base Arguments +- `--dit`: LTX-2 base model checkpoint (required). +- `--lora_weight`: One or more LoRA paths to merge sequentially (required). +- `--lora_multiplier`: Per-LoRA multipliers (default: all 1.0). +- `--save_merged_model`: Output merged model path (required). +- `--device cpu|cuda`: Device for merge computation (default: cuda). Pass `--device cpu` to run on system RAM if you don't have enough VRAM. +- `--audio_video`: Load as audio-video model (for LTXAV checkpoints). + +### Merge-to-Base Notes +- The output contains only transformer weights (VAE, vocoder, and text encoder are loaded separately by training/inference scripts). +- Original checkpoint metadata is preserved, so the merged file is directly usable with `--ltx2_checkpoint`. +- FP8 base models cannot be merged directly — merge into the bf16 base, then use `--fp8_base` at training time for on-the-fly quantization. + +--- + +## Merge LTX-2 LoRAs + +Use the dedicated LTX-2 LoRA merger to combine multiple LoRA files into a single LoRA checkpoint. + +**Script:** `ltx2_merge_lora.py` + +### Example Command (Windows) +```bash +python ltx2_merge_lora.py ^ + --lora_weight path/to/lora_A.safetensors path/to/lora_B.safetensors ^ + --lora_multiplier 1.0 1.0 ^ + --save_merged_lora path/to/merged_lora.safetensors +``` + +When merging multiple LoRAs that overlap on certain modules and only the first input's weights should win for the matched modules, pass a regex to `--preserve_first_match_pattern`: +```bash +python ltx2_merge_lora.py ^ + --lora_weight path/to/first.safetensors path/to/second.safetensors ^ + --preserve_first_match_pattern video_to_audio_attn ^ + --save_merged_lora path/to/merged_lora.safetensors +``` + +### LoRA Merge Arguments +- `--lora_weight`: Input LoRA paths to merge in order (required). +- `--lora_multiplier`: Per-LoRA multipliers aligned with `--lora_weight`. Use one value to apply the same multiplier to all inputs. +- `--save_merged_lora`: Output merged LoRA path (required). +- `--merge_method concat|orthogonal`: Merge method (default: `concat`). `concat` keeps all ranks by concatenation. `orthogonal` uses SVD refactorization to merge exactly 2 LoRAs with orthogonal projection. +- `--orthogonal_k_fraction`: Fraction of top singular directions projected out bilaterally before combining (default: `0.5`, range `[0, 1]`). Only used with `--merge_method orthogonal`. +- `--orthogonal_rank_mode sum|max|min`: Target rank mode for orthogonal merge (default: `sum`). +- `--preserve_first_match_pattern`: Regex matched against LoRA module prefixes. Matching modules keep only the first input LoRA that contains that module; later LoRAs are ignored for those modules. +- `--dtype auto|float32|float16|bfloat16`: Output tensor dtype. `auto` promotes from input dtypes. +- `--emit_alpha`: Force writing `.alpha` keys in output. + +### LoRA Merge Notes +- This merger is intended for LTX-2 LoRA formats used in this repo, including Comfy-style `lora_A/lora_B` weights. +- It handles different ranks and partial module overlap across input LoRAs. +- Orthogonal merge requires exactly 2 input LoRAs. + +--- + +## Dataset Configuration + +The dataset config is a TOML file with `[general]` defaults and `[[datasets]]` entries. Common options shared across all musubi-tuner architectures — including `frame_extraction` modes, JSONL metadata format, control image support, and resolution bucketing — are documented in the [Dataset Configuration guide](./dataset_config.md). The options below are LTX-2-specific or supplement base defaults. + +### Image Dataset Notes + +Image datasets use the common image schema from [Dataset Configuration](./dataset_config.md), including +`image_directory` or `image_jsonl_file`. For LTX-2 IC-LoRA with image datasets, use `reference_directory` +and `reference_cache_directory`. Internally this is normalized onto the shared image control path, so +other non-IC image workflows can continue using `control_directory`. + +### Video Dataset Options + +| Option | Type | Default | Description | +|--------|------|---------|-------------| +| `video_directory` | string | — | Path to video directory | +| `video_jsonl_file` | string | — | Path to JSONL metadata file | +| `resolution` | int or [int, int] | [960, 544] | Target resolution | +| `target_frames` | [int] | [1] | List of target frame counts | +| `frame_extraction` | string | `"head"` | Frame extraction mode | +| `max_frames` | int | 129 | Maximum number of frames | +| `source_fps` | float | auto-detected | Source video FPS. Auto-detected from video container metadata when not set. Use this to override auto-detection. | +| `target_fps` | float | 25.0 | Target training FPS. Frames are resampled to this rate. When audio is present and the source video has a different FPS, the audio waveform is automatically time-stretched (pitch-preserving) to match the target video duration. | +| `batch_size` | int | 1 | Batch size | +| `num_repeats` | int | 1 | Dataset repetitions | +| `enable_bucket` | bool | false | Enable resolution bucketing | +| `bucket_no_upscale` | bool | false | Prevent upscaling when bucketing (only downscale to fit) | +| `cache_directory` | string | — | Latent cache output directory | +| `reference_directory` | string | — | Reference images/videos for IC-LoRA (matched by filename) | +| `reference_cache_directory` | string | — | Output directory for cached reference latents (IC-LoRA) | +| `reference_audio_directory` | string | — | Reference audio files for audio-reference IC-LoRA (matched by filename stem) | +| `reference_audio_cache_directory` | string | — | Output directory for cached reference audio latents | +| `separate_audio_buckets` | bool | false | Keep audio/non-audio items in separate batches | +| `loss_mask_directory` | string | — | Optional stem-matched image/video masks for masked loss | +| `default_loss_mask_path` | string | — | Optional fallback image/video mask | +| `loss_mask_use_alpha` | bool | false | Image datasets only: use target image alpha as the mask when no mask directory is set | +| `loss_mask_invert` | bool | false | Invert image/video masks before caching | + +### Audio Dataset Options + +Audio-only datasets use `audio_directory` instead of `video_directory`. + +| Option | Type | Default | Description | +|--------|------|---------|-------------| +| `audio_directory` | string | — | Path to audio file directory | +| `audio_jsonl_file` | string | — | Path to JSONL metadata file | +| `audio_bucket_strategy` | string | `"pad"` | `"pad"` (round-to-nearest, pad + mask) or `"truncate"` (floor, clip to bucket length) | +| `audio_bucket_interval` | float | 2.0 | Bucket step size in seconds | +| `batch_size` | int | 1 | Batch size | +| `num_repeats` | int | 1 | Dataset repetitions | +| `cache_directory` | string | — | Latent cache output directory | +| `loss_mask_directory` | string | — | Optional stem-matched JSON/TXT/CSV interval masks | +| `default_loss_mask_path` | string | — | Optional fallback interval mask file | + +### Masked Loss Datasets + +Masked loss is configured in the dataset TOML and applied automatically during latent/audio caching. Training then reads `video_loss_mask` and `audio_loss_mask` from the cache and multiplies them with any masks already required by the selected training mode. This means masked loss works with standard video/image training, first-frame conditioning, v2v / IC-LoRA variants, audio-only training, and AV training. In IC-LoRA modes, masks are applied to target loss only; reference and conditioning tokens remain excluded from loss where the IC mode already excludes them. + +If no mask options are set, the cache output and training behavior are unchanged. + +Image/video masks: +- White means full loss, black means no loss, and grayscale values are soft weights. +- `loss_mask_directory` matches masks by source filename stem. +- JSONL datasets may use per-item `loss_mask_path` / `image_loss_mask_path` / `video_loss_mask_path`. +- A single image mask can be used for all frames, or a video/image-sequence mask can be used for frame-varying masks. + +Audio masks: +- Use intervals in seconds via JSONL `loss_mask_intervals` / `audio_loss_mask_intervals`. +- Or set `loss_mask_path` / `audio_loss_mask_path` to a JSON/TXT/CSV interval file. +- Directory datasets can use `loss_mask_directory` with stem-matched interval files. + +Examples: + +```toml +[[datasets]] +video_directory = "videos" +cache_directory = "cache" +caption_extension = ".txt" +target_frames = [33] +loss_mask_directory = "video_masks" +``` + +```json +{"audio_path":"audio/line.wav","caption":"voice","loss_mask_intervals":[[0.25, 1.8], [2.4, 3.1]]} +``` + +When a loss mask is configured, the training loop logs the mask-active fraction in the progress bar (`mv_act` / `ma_act`) and emits `loss/video_mask_active`, `loss/video_loss_unmasked`, `loss/video_loss_masked` (and audio equivalents) to TensorBoard / WandB. The pre- vs post-mask loss values make it visible whether the mask is actually shifting the gradient. + +### Example TOML + +```toml +[general] +resolution = [768, 512] +caption_extension = ".txt" +batch_size = 1 +enable_bucket = true +cache_directory = "cache" + +[[datasets]] +video_directory = "videos" +target_frames = [1, 17, 33, 49] +target_fps = 25 # optional, defaults to 25 +``` + +### Frame Rate (FPS) Handling + +During latent caching, the source FPS is **auto-detected** from each video's container metadata and frames are resampled to `target_fps` (default: 25). The model receives video at the configured temporal rate regardless of the source material. + +#### How It Works + +1. For each video file, the source FPS is read from the container metadata (`average_rate` or `base_rate`). +2. If `abs(ceil(source_fps) - target_fps) > 1`, frames are resampled (dropped) to match `target_fps`. +3. If the difference is within this threshold (e.g., 23.976 → ceil=24 vs target 25, diff=1), no resampling is done — this avoids spurious frame drops from NTSC rounding (23.976, 29.97, 59.94, etc.). +4. If audio is present (`--ltx2_mode av`), the audio waveform is automatically time-stretched (pitch-preserving) to match the resampled video duration. + +#### Common Scenarios + +**Default — no FPS config needed:** +```toml +[[datasets]] +video_directory = "videos" +target_frames = [1, 17, 33, 49] +# source_fps: auto-detected per video +# target_fps: defaults to 25 +``` +A 60fps video is resampled to 25fps. A 30fps video is resampled to 25fps. A 25fps video is passed through as-is. Mixed-FPS datasets work correctly — each video is resampled independently. + +**Training at a non-standard frame rate (e.g., 60fps):** +```toml +[[datasets]] +video_directory = "videos_60fps" +target_frames = [1, 17, 33, 49] +target_fps = 60 +``` +Set `target_fps` to the desired training rate. Videos at 60fps (or 59.94fps) pass through without resampling. Videos at other frame rates are resampled to 60fps. + +**Overriding auto-detection (e.g., variable frame rate videos):** +```toml +[[datasets]] +video_directory = "videos" +target_frames = [1, 17, 33, 49] +source_fps = 30 +``` +If auto-detection gives wrong results (common with variable frame rate / VFR recordings from phones), set `source_fps` explicitly. This applies to **all** videos in that dataset entry, so group videos by FPS into separate `[[datasets]]` blocks if needed. + +**Image directories:** + +Image directories have no FPS metadata. No resampling is applied — all images are loaded as individual frames regardless of `target_fps`. + +#### Log Messages + +During latent caching, log messages confirm what's happening for each video: +``` +Auto-detected source FPS: 60.00 for my_video.mp4 +Resampling my_video.mp4: 60.00 FPS -> 25.00 FPS +``` +If you see **no** "Resampling" line for a video, it means source and target FPS were close enough (within 1 FPS after rounding up the source) and all frames were kept as-is. If you see unexpected frame counts in your cached latents, check these log lines first. + +#### Quick Reference + +| Your situation | What to set | What happens | +|---|---|---| +| Mixed FPS dataset, want 25fps training | Nothing (defaults work) | Each video auto-detected, resampled to 25fps | +| All videos are 25fps | Nothing | Auto-detected as 25fps, no resampling | +| All videos are 60fps, want 60fps training | `target_fps = 60` | Auto-detected as 60fps, no resampling | +| All videos are 60fps, want 25fps training | Nothing | Auto-detected as 60fps, resampled to 25fps | +| VFR videos with wrong detection | `source_fps = 30` (your actual FPS) | Overrides auto-detection | +| Image directory | Nothing | No FPS concept, all images loaded | + +--- + +## Validation Datasets + +> [!NOTE] +> Validation datasets are an extension specific to this LTX-2 trainer. + +You can configure a separate validation dataset to track validation loss (`val_loss`) during training. This helps detect overfitting and compare training runs. Validation datasets use **exactly the same schema** as training datasets — any format that works for `[[datasets]]` works for `[[validation_datasets]]`. + +### Configuration + +Add a `[[validation_datasets]]` section to your existing TOML config file: + +```toml +[general] +resolution = [768, 512] +caption_extension = ".txt" +batch_size = 1 +enable_bucket = true + +# Training data +[[datasets]] +video_directory = "videos/train" +cache_directory = "cache/train" +target_frames = [1, 17, 33, 49] + +# Validation data +[[validation_datasets]] +video_directory = "videos/val" +cache_directory = "cache/val" +target_frames = [1, 17, 33, 49] +``` + +Use a separate `cache_directory` for validation data to avoid mixing training and validation cache files. + +### Caching + +Validation datasets are automatically picked up by the caching scripts — no extra flags needed. Run the same caching commands you use for training: + +```bash +python ltx2_cache_latents.py --dataset_config dataset.toml --ltx2_checkpoint /path/to/ltx-2.safetensors --ltx2_mode av ... +python ltx2_cache_text_encoder_outputs.py --dataset_config dataset.toml --ltx2_checkpoint /path/to/ltx-2.safetensors --ltx2_mode av ... +``` + +Both scripts detect the `[[validation_datasets]]` section and cache latents/text embeddings for validation data alongside training data. + +### Training Arguments + +| Argument | Type | Default | Description | +|----------|------|---------|-------------| +| `--validate_every_n_steps` | int | None | Run validation every N training steps | +| `--validate_every_n_epochs` | int | None | Run validation every N epochs | +| `--offload_optimizer_during_validation` | flag | off | Temporarily move CUDA optimizer state to CPU while validation/sample previews run | + +At least one of these must be set for validation to run. If neither is set, validation is skipped even if `[[validation_datasets]]` is configured. + +### Example + +```bash +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 ltx2_train_network.py ^ + --dataset_config dataset.toml ^ + --validate_every_n_steps 100 ^ + ... (other training args) +``` + +### How It Works + +1. A separate validation dataloader is created with `batch_size=1` and `shuffle=False` (deterministic order). +2. At the configured interval, the model switches to eval mode and runs inference on all validation samples with `torch.no_grad()`. +3. The average validation loss is computed with the active `--loss_type` and logged as `val_loss` to TensorBoard/WandB. +4. The model is restored to training mode and training continues. + +### Tips + +- **Keep validation sets small.** Aim for 5-20% of your main dataset size. Validation runs on every sample each time, so 10-50 clips is usually enough. Large validation sets slow down training. +- **Use held-out data.** Validation data should be different from the training set for meaningful overfitting detection. In extreme cases, using a small subset of the training data is acceptable — it will still help catch divergence, but won't reliably detect overfitting. +- **Monitor the gap.** If `val_loss` starts increasing while training loss keeps decreasing, you're overfitting — consider stopping or reducing the learning rate. +- **Same preprocessing.** Validation data goes through the same frame extraction, FPS resampling, and resolution bucketing as training data. + +--- + +## Directory Structure + +### Raw Dataset Layout (Example) +``` +dataset_root/ + videos/ + 000001.mp4 + 000001.txt # caption + 000002.mp4 + 000002.txt +``` + +### Cache Directory Layout (After Caching) +``` +cache_directory/ + 000001_1024x0576_ltx2.safetensors # video latents + 000001_ltx2_te.safetensors # text encoder outputs + 000001_ltx2_audio.safetensors # audio latents (av mode only) + 000001_1024x0576_ltx2_dino.safetensors # DINOv2 features (CREPA dino mode only) + +reference_cache_directory/ # IC-LoRA only + 000001_1024x0576_ltx2.safetensors # reference latents +``` + +--- + +## Troubleshooting + +| Error | Cause | Solution | +|-------|-------|----------| +| Missing cache keys during training | Caching incomplete | Run both `ltx2_cache_latents.py` and `ltx2_cache_text_encoder_outputs.py` | +| FlashAttention varlen mask-length mismatch (for example `expects mask length 1920, got 1024`) after checkpoint switch | Stale text cache from a different checkpoint/version/mode | Re-run `ltx2_cache_text_encoder_outputs.py` with the same `--ltx2_checkpoint` and `--ltx2_mode` as training. Remove old `*_ltx2_te.safetensors` if needed. | +| Samples become progressively noisier/degraded when training with `--flash_attn` | FlashAttention install/runtime mismatch (CUDA/PyTorch/flash-attn build) | Switch to `--sdpa` to confirm baseline stability. If SDPA is stable, reinstall FlashAttention for your exact CUDA + PyTorch versions and retry. | +| Training fails after changing `--ltx2_checkpoint` even though args look correct | Reused latent/text caches generated from a different checkpoint | Re-run both caches (`ltx2_cache_latents.py` and `ltx2_cache_text_encoder_outputs.py`) and regenerate `--dataset_manifest` before training. | +| OOM appears after removing `--fp8_base` while using an FP8 checkpoint | Base model no longer uses FP8 loading path, so VRAM increases sharply | Keep `--fp8_base` enabled for FP8 checkpoints (typically with `--mixed_precision bf16`) | +| Error when combining `--fp8_scaled` with an FP8 checkpoint (old behavior) | Checkpoint has FP8 weights without `weight_scale` keys (non-standard format) | Use a standard bf16 checkpoint, or a properly exported FP8 checkpoint that includes scale tensors | +| Missing `*_ltx2_audio.safetensors` | Audio caching skipped | Re-run latent caching with `--ltx2_mode av` | +| Gemma connector weights missing | Incorrect checkpoint | Ensure `--ltx2_checkpoint` (or `--ltx2_text_encoder_checkpoint`) contains Gemma connector weights | +| Gemma OOM | Model too large | Use `--gemma_load_in_8bit` or `--gemma_load_in_4bit` with `--device cuda`, or use `--gemma_safetensors` with an FP8 file | +| Startup OOM with `--dop` or `--blank_preservation` | Live preservation-prompt encoding briefly loads Gemma alongside the model; DOP/blank preservation do not need Gemma after startup. | Precache with `--precache_preservation_prompts`, then train with `--use_precached_preservation`. | +| Audio caching fails | torchaudio missing | Install torchaudio before running `ltx2_cache_latents.py` | +| Sampling OOM | VAE decode too large | Enable `--sample_tiled_vae` or reduce `--sample_vae_temporal_tile_size` | +| Crash with block swap (esp. RTX 5090) | `--use_pinned_memory_for_block_swap` bug | Remove `--use_pinned_memory_for_block_swap` from training arguments | +| `stack expects each tensor to be equal size` during AV training | Mixed audio/non-audio videos in the same batch — text embeddings are 2×`caption_channels` for AV items vs 1×`caption_channels` for video-only (e.g., 7680 vs 3840 for LTX-2.3), and `torch.stack` fails | Add `--separate_audio_buckets` to training args. Required when your dataset mixes videos with and without audio at `batch_size > 1`. At `batch_size=1` it has no effect. | +| Wrong frame count in cached latents | Auto-detected FPS incorrect (e.g., VFR video) | Set `source_fps` explicitly in TOML config to override auto-detection | +| Too few frames from high-FPS video | FPS resampling working correctly (e.g., 60fps→25fps = 42% of frames) | Expected behavior. Set `target_fps = 60` if you want to keep all frames | +| Audio/video out of sync after caching | Source FPS mismatch causing wrong time-stretch | Check "Auto-detected source FPS" log line; set `source_fps` explicitly if wrong | +| Voice/audio learning slow when mixing images with videos in AV mode | Image batches produce zero audio training signal — audio branch is skipped entirely. Dilutes audio learning proportionally to image step fraction | Use video-only datasets for AV training when voice quality matters | +| No audio during sampling in video training mode | `ltx2_mode` is set to `v`/`video` | Expected behavior. Train in AV mode (`--ltx2_mode av` or `audio`) to generate audio during sampling | +| Cannot resume training from checkpoint | Using a `*.comfy.safetensors` checkpoint with `--resume` | Training can only be resumed from the **original** (non-comfy) LoRA format. Use the `*.safetensors` file without the `.comfy` extension. If you used `--no_save_original_lora`, you must retrain from scratch. | +| CUDA errors or crashes on RTX 5090 / 50xx GPUs | CUDA 12.6 (`cu126`) not supported on Windows for Blackwell GPUs | Use CUDA 12.8: `pip install torch==2.8.0 ... --index-url https://download.pytorch.org/whl/cu128`. See [CUDA Version](#cuda-version) | +| `ValueError: Gemma safetensors is missing required language-model tensors` with `missing_buffers` mentioning `full_attention_inv_freq` or `sliding_attention_inv_freq` | `transformers>=5.0` renamed Gemma3 rotary embedding buffers (`rotary_emb.inv_freq` → `rotary_emb.full_attention_inv_freq` / `sliding_attention_inv_freq`). The derivable-buffer suffix check expects `.inv_freq` and does not match the new `_inv_freq` suffix. The safetensors file is correct — rotary buffers are non-persistent and computed from config at init time. | `pip install transformers==4.56.1` (pinned in `pyproject.toml`), or reinstall all deps with `pip install -e .` | +| Audio quality degrades after training video/image LoRA on an AV checkpoint | Default `t2v` preset creates LoRA weights for audio and cross-modal attention layers. With no audio training data, those weights are initialized but receive no meaningful gradient signal — applying the LoRA overwrites audio layers with near-zero deltas that disrupt the base model's audio representations. | Use a `video_*` preset (`--lora_target_preset video_sa`, `video_sa_ff`, or `video_sa_ca_ff`) to restrict LoRA to video-branch modules only. Audio layers remain frozen and unmodified. See [LoRA Targets](#lora-targets). | +| `loss_a` too low but `loss_v` still high (audio overfitting) | Audio latent space converges faster than video; audio gradients dominate shared weights | Lower `--audio_loss_weight` (e.g., 0.3), or use `--audio_loss_balance_mode ema_mag` to auto-dampen audio when it exceeds `target_ratio × video_loss`. Reduce audio learning rate with `--audio_lr 1e-6` or fine-grained `--lr_args audio_attn=1e-6 audio_ff=1e-6`. Disable `--audio_dop` / `--audio_silence_regularizer` if active — they add more audio signal. | +| `loss_a` absent or not dropping in mixed dataset (audio starvation) | Audio batches too rare — non-audio steps outnumber audio steps, audio branch gets insufficient supervision | Increase `num_repeats` on audio datasets (target 30-50% audio steps). Add `--audio_loss_balance_mode inv_freq` to auto-boost audio weight. Use `--audio_dop` or `--audio_silence_regularizer` to provide audio signal on non-audio steps. Check caching summary for `failed > 0`. | + +### Mixed Audio-Video Training + +Use this section for joint AV LoRA (`--ltx2_mode av`) when the dataset mixes audio-bearing clips with silent, video-only, image, or reference-conditioned samples. The common failure modes are audio starvation (`loss_a` is absent or rare) and audio overfitting (`loss_a` drops much faster than `loss_v` while video, identity, or motion quality drifts). These controls are training-only; the saved LoRA loads normally at inference. + +**1. Keep audio batches visible.** Use dataset `num_repeats` so audio-bearing clips are not outnumbered by non-audio samples: +```toml +[[datasets]] +video_directory = "audio_video_clips" +num_repeats = 5 +``` + +You can also use the audio-aware sampler when both audio and non-audio batches are available: +```bash +--audio_batch_probability 0.4 +``` +With gradient accumulation, prefer a hard quota: +```bash +--gradient_accumulation_steps 4 --min_audio_batches_per_accum 1 +``` +Do not combine `--audio_batch_probability` / `--min_audio_batches_per_accum` with `--accumulation_group_by`; both need to own DataLoader sampling. See [Audio-Video Support](#audio-video-support). + +**2. Separate incompatible batches.** Use `--separate_audio_buckets` when audio and non-audio items share a dataset at `batch_size > 1`. This avoids text-embedding shape mismatches and keeps non-audio batches cheaper. + +**3. Lower audio learning rate.** Audio modules may need a lower LR than video modules in mixed AV runs. Use `--audio_lr` for a broad audio-side override or `--lr_args` for module-level control: +```bash +--learning_rate 1e-4 --audio_lr 3e-5 +``` + +**4. Lower audio LoRA rank.** Use `--audio_dim` / `--audio_alpha` when audio modules should have less adaptation capacity than video modules: +```bash +--network_dim 32 --audio_dim 8 --audio_alpha 8 +``` + +**5. Balance audio/video losses.** `--audio_loss_balance_mode` controls dynamic audio loss weighting: +- `inv_freq`: scales audio by inverse audio-batch frequency EMA; useful when audio batches are rare. +- `ema_mag`: tracks audio/video loss EMAs and scales audio toward `--audio_loss_balance_target_ratio`; can boost or dampen audio. +- `uncertainty`: learns two log-variance scalars jointly with LoRA parameters. +- `ogm_ge`: attenuates the lower-loss / faster-learning modality on each AV step. + +Examples: +```bash +--audio_loss_balance_mode inv_freq --audio_loss_balance_min 0.05 --audio_loss_balance_max 4.0 +``` +```bash +--audio_loss_balance_mode ema_mag --audio_loss_balance_target_ratio 0.33 +``` + +For audio-starved runs, combine `inv_freq` with the supervision monitor: +```bash +--audio_loss_balance_mode inv_freq ^ +--audio_supervision_mode warn ^ +--audio_supervision_min_ratio 0.5 +``` + +When audio overfits before video, combine a lower audio LR/rank with `ema_mag`: +```bash +--learning_rate 1e-4 --audio_lr 3e-5 ^ +--network_dim 32 --audio_dim 8 --audio_alpha 8 ^ +--audio_loss_balance_mode ema_mag ^ +--audio_loss_balance_target_ratio 0.25 +``` + +**6. Add signal on non-audio steps only when needed.** `--audio_dop` preserves base audio predictions on non-audio batches. It runs LoRA-off and LoRA-on forwards on synthetic silence audio latents, logs `loss/audio_dop`, and has no cost on batches that already contain audio: +```bash +--audio_dop --audio_dop_args multiplier=0.5 +``` + +`--audio_silence_regularizer` instead trains missing-audio batches toward silence. It is cheaper than Audio DOP, but silence is a training target rather than a preservation reference: +```bash +--audio_silence_regularizer --audio_silence_regularizer_weight 0.5 +``` + +`--audio_dop` and `--audio_silence_regularizer` are mutually exclusive. Prefer checking sampler balance and `loss_a` first, because both add extra audio supervision. + +**7. Drop modality text conditioning independently.** Per-modality caption dropout can regularize AV conditioning and train mixed conditional states: +```bash +--video_caption_dropout_rate 0.05 --audio_caption_dropout_rate 0.10 +``` + +This can be combined with the audio-aware sampler, `--audio_loss_balance_mode ema_mag`, and `--dcr`. + +**8. Freeze the faster modality when it dominates.** Modality freezing toggles audio/video LoRA parameters based on the audio/video loss EMA ratio: +```bash +--modality_freeze_check_interval 500 ^ +--modality_freeze_ratio_threshold 0.5 ^ +--modality_freeze_warmup_steps 200 +``` + +Logged metrics include `modality_freeze/state`, `modality_freeze/video_loss_ema`, and `modality_freeze/audio_loss_ema`. + +**9. Use Self-Flow when representation alignment is part of the run.** `--self_flow` can add video and audio representation-alignment terms in AV mode. Keep its detailed setup in the [Self-Flow](#self-flow-self-supervised-flow-matching) section, and only enable audio alignment when you intentionally want that extra objective: +```bash +--self_flow --self_flow_args lambda_self_flow=0.1 lambda_audio=0.1 teacher_mode=base +``` + +**10. Route cross-modal gradients deliberately for `av_ic` and sync-sensitive runs.** `--dcr --dcr_args reference_detach=true` can be combined with the audio-aware sampler, `ema_mag`, and per-modality caption dropout. Add `--tarp` or Cross-Task Synergy only when AV sync or cross-modal alignment is the target and the compute cost is acceptable: +```bash +--dcr --dcr_args reference_detach=true +``` +```bash +--cts_lambda_video_driven 0.3 --cts_lambda_audio_driven 0.1 +``` + +**11. Override warmup by optimizer group when needed.** Per-group warmup keeps the same scheduler family but can stretch warmup differently for audio and video groups: +```bash +--lr_group_warmup_args audio=500 video=1500 +``` + +**12. Check the basics before scaling.** +- If `failed > 0` in latent caching summary, audio extraction is broken for those items. +- After switching from video-only to AV mode, re-run both latent and text encoder caching without `--skip_existing`. +- `loss_a` dropping means audio is learning; absent/zero usually means no audio batches are forming; degradation over time can indicate forgetting. +- Track `grad_norm/video`, `grad_norm/audio`, and `grad_norm/audio_video_ratio` during AV runs. + +### Technical Notes + +- **Float32 AdaLN**: The transformer applies Adaptive Layer Norm (AdaLN) shift/scale operations in float32, then casts back to the working dtype. This prevents overflow that can occur when bf16 scale values multiply bf16 hidden states. The fix is always active and requires no flags. +- **Loss dtype**: The LTX-2 training path computes the task loss (MSE, L1, Huber) in `trainer.dit_dtype` (typically bf16 with `--mixed_precision bf16`). Internal regularization losses (motion preservation, CREPA, Self-Flow, latent temporal objectives) always use their own configured loss and are unaffected by global `--loss_type`. + +For additional troubleshooting resources, see the [LTX-2 documentation hub](https://docs.ltx.video/open-source-model/getting-started/overview), the [Banodoco Discord](https://discord.gg/banodoco) community, and the [awesome-ltx2](https://github.com/wildminder/awesome-ltx2) curated resource list. + +--- + +## 4. Slider LoRA Training + +> Slider LoRA training is based on the [ai-toolkit](https://github.com/ostris/ai-toolkit) implementation by ostris, adapted for LTX-2. + +Slider LoRAs learn a controllable direction in model output space (e.g., "detailed" vs "blurry"). At inference, you scale the LoRA multiplier to control the effect strength and direction: `+1.0` enhances, `-1.0` erases, `0.0` is the base model, and values like `+2.0` or `-0.5` work too. + +**Script:** `ltx2_train_slider.py` + +Three modes are available: + +| Mode | Input | Use Case | +|------|-------|----------| +| `text` | Prompt pairs only (no dataset) | Sliders from text prompt pairs, no images needed | +| `reference` | Pre-cached latent pairs | Sliders from paired positive/negative image, video, or audio samples | +| IC-slider (`mode = "ic_reference"`) | Paired target caches + shared reference caches | Slider training under shared `v2v` reference conditioning | + +### 4a. Text-Only Mode + +Learns a slider direction from positive/negative prompt pairs. No images or dataset config needed. + +#### Slider Config (`ltx2_slider.toml`) + +```toml +mode = "text" +guidance_strength = 1.0 +sample_slider_range = [-2.0, -1.0, 0.0, 1.0, 2.0] + +[[targets]] +positive = "extremely detailed, sharp, high resolution, 8k" +negative = "blurry, out of focus, low quality, soft" +target_class = "" # empty = affect all content +weight = 1.0 +``` + +- `guidance_strength`: Scales the directional offset applied to targets. Higher values = stronger direction signal but may overshoot. +- `target_class`: The conditioning prompt used during training passes. Empty string means the slider affects all content regardless of prompt. Set to e.g. `"a portrait"` to restrict the slider's effect to a specific subject. +- `weight`: Per-target loss weight. Controls relative emphasis when training multiple directions simultaneously. +- `sample_slider_range`: Multiplier values used for preview samples during training. + +Multiple `[[targets]]` blocks can be defined to train several directions at once (e.g., detail + lighting). + +#### Example Command (Text-Only) + +```bash +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 ltx2_train_slider.py ^ + --mixed_precision bf16 ^ + --ltx2_checkpoint /path/to/ltx-2.safetensors ^ + --gemma_root /path/to/gemma ^ + --gemma_load_in_8bit ^ + --fp8_base --fp8_scaled ^ + --gradient_checkpointing ^ + --blocks_to_swap 10 ^ + --network_module networks.lora_ltx2 ^ + --network_dim 16 --network_alpha 16 ^ + --lora_target_preset t2v ^ + --learning_rate 1e-4 ^ + --optimizer_type AdamW8bit ^ + --lr_scheduler constant_with_warmup --lr_warmup_steps 20 ^ + --max_train_steps 500 ^ + --output_dir output --output_name detail_slider ^ + --slider_config ltx2_slider.toml ^ + --latent_frames 1 ^ + --latent_height 512 --latent_width 768 +``` + +#### Text-Only Arguments + +| Argument | Default | Description | +|----------|---------|-------------| +| `--slider_config` | (required) | Path to slider TOML config file | +| `--latent_frames` | 1 | Number of latent frames (1=image, >1=video) | +| `--latent_height` | 512 | Pixel height for synthetic latents | +| `--latent_width` | 768 | Pixel width for synthetic latents | +| `--guidance_strength` | (from TOML) | Override `guidance_strength` from config | +| `--sample_slider_range` | (from TOML) | Override as comma-separated values, e.g. `"-2,-1,0,1,2"` | + +All standard training arguments (`--fp8_base`, `--blocks_to_swap`, `--gradient_checkpointing`, etc.) work the same as regular training. `--dataset_config` is not needed for text-only mode. + +### 4b. Reference Mode + +Learns a slider direction from paired positive/negative image, video, or audio examples. Requires pre-cached latents. + +#### Step 1: Prepare Paired Data + +Create two directories with matching filenames — one with positive-attribute images, one with negative: + +``` +positive_images/ negative_images/ + img_001.png img_001.png # same subject, different attribute + img_002.png img_002.png + img_003.png img_003.png +``` + +Each positive image must have a corresponding negative image with the same filename. The images should depict the same subject but differ in the target attribute (e.g., smiling vs neutral face, detailed vs blurry). + +For image-based sliders, cache these paired images normally and keep `reference_modality = "video"` (the visual latent path covers both single-frame images and multi-frame videos). + +#### Step 2: Cache Latents and Text + +Create a dataset config for each directory and run the caching scripts. Both directories can share the same text captions (since the direction comes from the images, not the text). + +```bash +# Cache positive latents +python ltx2_cache_latents.py --dataset_config positive_dataset.toml --ltx2_checkpoint /path/to/ltx-2.safetensors + +# Cache negative latents +python ltx2_cache_latents.py --dataset_config negative_dataset.toml --ltx2_checkpoint /path/to/ltx-2.safetensors + +# Cache text (once, for either directory — text is shared) +python ltx2_cache_text_encoder_outputs.py --dataset_config positive_dataset.toml --ltx2_checkpoint /path/to/ltx-2.safetensors --gemma_root /path/to/gemma +``` + +#### Step 3: Configure and Train + +##### Slider Config (`ltx2_slider_reference.toml`) + +```toml +mode = "reference" +reference_modality = "video" # "video" or "audio" +pos_cache_dir = "path/to/positive/cache" +neg_cache_dir = "path/to/negative/cache" +text_cache_dir = "path/to/positive/cache" # can be same as pos (text is shared) +sample_slider_range = [-2.0, -1.0, 0.0, 1.0, 2.0] +``` + +- `reference_modality`: `video` for image/video latent pairs, `audio` for paired audio latents +- `pos_cache_dir`: Directory containing cached positive latents (output of `ltx2_cache_latents.py`) +- `neg_cache_dir`: Directory containing cached negative latents +- `text_cache_dir`: Directory containing cached text encoder outputs. Defaults to `pos_cache_dir` if omitted. + +Video pairs are matched by filename: for each `{name}_{W}x{H}_ltx2.safetensors` in the positive directory, a matching file must exist in the negative directory. + +Audio pairs are matched by filename: for each `{name}_ltx2_audio.safetensors` in the positive directory, a matching audio file must exist in the negative directory, and both directories must also contain the companion audio-only virtual geometry cache `{name}_{W}x{H}_ltx2.safetensors`. Unmatched files are skipped with a warning. + +##### Example Command (Reference) + +```bash +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 ltx2_train_slider.py ^ + --mixed_precision bf16 ^ + --ltx2_checkpoint /path/to/ltx-2.safetensors ^ + --fp8_base --fp8_scaled ^ + --gradient_checkpointing ^ + --blocks_to_swap 10 ^ + --network_module networks.lora_ltx2 ^ + --network_dim 16 --network_alpha 16 ^ + --lora_target_preset t2v ^ + --learning_rate 1e-4 ^ + --optimizer_type AdamW8bit ^ + --lr_scheduler constant_with_warmup --lr_warmup_steps 20 ^ + --max_train_steps 500 ^ + --output_dir output --output_name smile_slider ^ + --slider_config ltx2_slider_reference.toml +``` + +Note: `--gemma_root` is not needed for reference mode (text embeddings are loaded from cache). `--dataset_config`, `--latent_frames/height/width` are also not used. + +For video reference sliders, `--ltx2_first_frame_conditioning_p` also works here. When enabled on multi-frame samples, the trainer anchors frame 0 as conditioning-only and excludes it from the loss, which is useful when positive/negative pairs share the same start frame and differ mainly in motion. It has no effect for text-only sliders or single-frame reference samples. + +##### Audio Reference Sliders + +For paired audio sliders, set `reference_modality = "audio"` and train in audio-only mode: + +```toml +mode = "reference" +reference_modality = "audio" +pos_cache_dir = "path/to/positive/audio_cache" +neg_cache_dir = "path/to/negative/audio_cache" +text_cache_dir = "path/to/positive/audio_cache" +sample_slider_range = [-2.0, -1.0, 0.0, 1.0, 2.0] +``` + +```bash +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 ltx2_train_slider.py ^ + --mixed_precision bf16 ^ + --ltx2_checkpoint /path/to/ltxav-2.safetensors ^ + --ltx2_mode audio ^ + --fp8_base --fp8_scaled ^ + --gradient_checkpointing ^ + --blocks_to_swap 10 ^ + --network_module networks.lora_ltx2 ^ + --network_dim 16 --network_alpha 16 ^ + --lora_target_preset audio ^ + --learning_rate 1e-4 ^ + --optimizer_type AdamW8bit ^ + --lr_scheduler constant_with_warmup --lr_warmup_steps 20 ^ + --max_train_steps 500 ^ + --sample_audio_only ^ + --output_dir output --output_name audio_energy_slider ^ + --slider_config ltx2_slider_audio_reference.toml +``` + +Notes: +- Audio reference sliders are an MVP path built for `--ltx2_mode audio`. +- The trainer uses the same paired positive/negative audio latents plus shared text cache, and masks loss with cached `audio_lengths`. +- `--lora_target_preset audio` is recommended; if omitted, the slider trainer selects it automatically for audio reference sliders. +- `--ltx2_first_frame_conditioning_p` has no effect for audio sliders. + +### 4c. IC-slider +Trains a slider from paired positive/negative target latents under a shared cached visual reference. Internally this mode reuses the existing `v2v` IC path. + +#### Slider Config (`ltx2_slider_ic_reference.toml`) + +```toml +mode = "ic_reference" +reference_modality = "video" +pos_cache_dir = "path/to/positive/cache" +neg_cache_dir = "path/to/negative/cache" +text_cache_dir = "path/to/text/cache" +reference_cache_dir = "path/to/reference/cache" +sample_slider_range = [-2.0, -1.0, 0.0, 1.0, 2.0] +``` + +- `pos_cache_dir`: Directory containing cached positive target latents. +- `neg_cache_dir`: Directory containing cached negative target latents. +- `text_cache_dir`: Directory containing cached text encoder outputs matched by basename. +- `reference_cache_dir`: Directory containing cached reference-video latents matched by basename. + +Current restrictions: +- `reference_modality = "video"` only +- `--ltx2_mode video` only +- `--ic_lora_strategy` resolves to `v2v` +- if `--lora_target_preset` is omitted, the trainer selects `v2v` + +Files are matched by basename. For each `{name}_{W}x{H}_ltx2.safetensors` in `pos_cache_dir`, the trainer expects: +- a matching negative latent file in `neg_cache_dir` +- a matching text cache `{name}_ltx2_te.safetensors` in `text_cache_dir` +- a matching reference latent file in `reference_cache_dir` + +##### Example Command (IC-Aware Reference) + +```bash +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 ltx2_train_slider.py ^ + --mixed_precision bf16 ^ + --ltx2_checkpoint /path/to/ltx-2.safetensors ^ + --ltx2_mode video ^ + --fp8_base --fp8_scaled ^ + --gradient_checkpointing ^ + --blocks_to_swap 10 ^ + --network_module networks.lora_ltx2 ^ + --network_dim 16 --network_alpha 16 ^ + --lora_target_preset v2v ^ + --learning_rate 1e-4 ^ + --optimizer_type AdamW8bit ^ + --lr_scheduler constant_with_warmup --lr_warmup_steps 20 ^ + --max_train_steps 500 ^ + --output_dir output --output_name identity_smile_slider ^ + --slider_config ltx2_slider_ic_reference.toml +``` + +Additional notes: +- `--ltx2_first_frame_conditioning_p` still applies on the target side +- AV and audio IC-slider variants are not implemented + +### Slider Tips + +- **Start small**: `--network_dim 8` or `16` with `--max_train_steps 200-500` is usually sufficient. +- **Monitor loss**: Loss usually trends downward once training is stable. If it diverges, reduce `--learning_rate`. +- **Preview samples**: Add `--sample_prompts sampling_prompts.txt --sample_every_n_steps 50` to generate previews at each slider strength during training. Requires `--gemma_root` for text encoding. For audio sliders, also use `--sample_audio_only`. +- **Guidance strength**: For text-only mode, the default is `1.0`. Values of `2.0-3.0` increase direction strength but may reduce convergence stability. +- **Multiple targets**: Text-only mode supports multiple `[[targets]]` blocks. Each step randomly selects one target, so all directions get trained evenly. +- **Inference**: Use the trained LoRA with any multiplier value. Positive multipliers enhance the positive attribute, negative multipliers enhance the negative attribute. Values beyond `[-1, +1]` extrapolate the effect. + +--- + +## Windows Setup / Update Script + +[`scripts/install.ps1`](https://github.com/AkaneTendo25/musubi-tuner/blob/ltx-2/scripts/install.ps1) is the Windows setup and maintenance entry point. + +> [!WARNING] +> The setup script, dashboard, and GUI are **experimental**. Their behavior, layout, and generated files may change between versions. Unsupported local environments may still need manual installation steps. Not all training and inference paths are wired through the dashboard — some advanced flags are CLI-only. + +The script can run these actions, depending on the selected options and current machine state: + +- install or locate `git`, Python, and Node.js/npm +- clone the repository, update an existing checkout, or switch the target branch with `-Branch` +- create the repo-local `venv` or reuse an existing `venv\Scripts\python.exe` +- install PyTorch for `cu124`, `cu128`, `cu130`, or `cpu`, then install the project with dashboard extras +- build the dashboard frontend with `npm install` and `npm run build` +- write `launch_musubi_dashboard.cmd` and `launch_musubi_setup.cmd` +- optionally create desktop shortcuts for the dashboard and setup/update launcher +- write `.musubi_install_state.json` for later setup/status checks +- optionally start the dashboard launcher at the end of the run + +**Interactive one-liner:** + +```powershell +irm https://raw.githubusercontent.com/AkaneTendo25/musubi-tuner/ltx-2/scripts/install.ps1 | iex +``` + +With no parameters, the script defaults to branch `ltx-2`, CUDA `cu128`, Python `3.12`, dashboard host `127.0.0.1`, and port `7860`. Interactive mode prints the detected environment and lets you choose which actions to run. + +**Saved script with explicit parameters:** + +```powershell +irm https://raw.githubusercontent.com/AkaneTendo25/musubi-tuner/ltx-2/scripts/install.ps1 -OutFile install.ps1 +.\install.ps1 -Cuda cu124 -PythonVersion 3.11 -NonInteractive +``` + +Available parameters: `-InstallRoot`, `-RepoUrl`, `-Branch`, `-RepoDir`, `-Cuda` (`cu124`/`cu128`/`cu130`/`cpu`), `-PythonVersion` (`3.10`/`3.11`/`3.12`/`3.13`), `-Port`, `-DashboardHost`, `-NonInteractive`, `-StrictPreflight`, and `-PreflightOnly`. + +Use `-PreflightOnly` to run the environment checks without making install changes. The script writes a timestamped log to `%TEMP%\musubi_ltx2_install_*.log`; on failure it prints a support bundle with the current step, exception details, and log path. + +### Dashboard Usage + +> [!NOTE] +> The dashboard GUI is experimental. Common training, caching, and inference flows are wired up; some advanced flags remain CLI-only. UI layout, validation messages, and dashboard metrics may change between versions. + +After the installer finishes, start the dashboard from the generated `Musubi Tuner Dashboard` desktop shortcut or from `launch_musubi_dashboard.cmd` in the repository directory. + +You can also start it manually from the repo-local virtual environment: + +```powershell +venv\Scripts\python.exe -m musubi_tuner.gui_dashboard --host 127.0.0.1 --port 7860 +``` + +Open the printed browser URL, usually `http://127.0.0.1:7860/`. + +Basic flow: + +- Use `Projects` to create or load a `project.json`. +- Use `Dataset` to define training and validation datasets. +- Use `Caching` to run latent, text encoder, and DINO cache jobs when needed. +- Use `Training` to configure LoRA training and start/stop the training process. +- Use `Samples` for training sample prompts. +- Use `Inference` to run inference from the selected project settings. +- Use `Settings` > `Setup & Updates` to view install status, launcher/shortcut status, repository status, and open the setup/update tool. + +When a cache, training, slider training, or inference job is started from the dashboard, the dashboard shows process status and logs. For training jobs started from the dashboard, the dashboard also reads the training metrics written by the trainer. + +--- + +## References + +**Musubi Tuner Documentation** +- [Dataset Configuration](./dataset_config.md) — TOML format, `frame_extraction` modes, JSONL metadata, control images, resolution bucketing +- [Sampling During Training](./sampling_during_training.md) — Prompt file format, per-prompt guidance scale, negative prompts, sampling CLI flags +- [Advanced Configuration](./advanced_config.md) — `--config_file` TOML training configuration, `--network_args` format, LoRA+, TensorBoard/WandB logging, PyTorch Dynamo, timestep bucketing, Schedule-Free optimizer +- [Tools](./tools.md) — Post-hoc EMA LoRA merging, image captioning with Qwen2.5-VL +- [LoHa/LoKr](./loha_lokr.md) — Alternative parameter-efficient fine-tuning methods +- [torch.compile](./torch_compile.md) — PyTorch JIT compilation for faster training and inference +- [LyCORIS Algorithm List](https://github.com/KohakuBlueleaf/LyCORIS/blob/main/docs/Algo-List.md) and [Guidelines](https://github.com/KohakuBlueleaf/LyCORIS/blob/main/docs/Guidelines.md) — LoKR, LoHA, LoCoN and other algorithm details (used via `pip install lycoris-lora`) + +**Research** +- [ID-LoRA](https://github.com/ID-LoRA/ID-LoRA) — In-context identity LoRA; the audio-reference IC-LoRA implementation in this trainer is based on this approach +- [QLoRA (arXiv 2305.14314)](https://arxiv.org/abs/2305.14314) — Introduces NF4 quantization used by the `--nf4_base` implementation +- [LoftQ (arXiv 2310.08659)](https://arxiv.org/abs/2310.08659) — Quantization-aware LoRA initialization used by `--loftq_init` +- [AWQ (arXiv 2306.00978)](https://arxiv.org/abs/2306.00978) — Activation-aware quantization background for `--awq_calibration` +- [DINOv2 (arXiv 2304.07193)](https://arxiv.org/abs/2304.07193) — External visual features used by CREPA dino mode +- [CREPA (arXiv 2506.09229)](https://arxiv.org/abs/2506.09229) — Cross-frame Representation Alignment; basis for `--crepa dino` mode (DINOv2 teacher from neighboring frames) +- [Latent Temporal Discrepancy (arXiv 2601.20504)](https://arxiv.org/abs/2601.20504) — Motion-prior loss weighting basis for `--latent_temporal_weighting` +- [CCL / TARP / DCR (arXiv 2603.18600)](https://arxiv.org/abs/2603.18600) — Cross-modal context learning; basis for `--tarp` and `--dcr` +- [Self-Flow (arXiv 2603.06507)](https://arxiv.org/abs/2603.06507) — Self-supervised flow matching regularization; basis for `--self_flow` +- [ViBe / HFATO / Relay LoRA (arXiv 2603.23326)](https://arxiv.org/abs/2603.23326) — Basis for `--hfato` and the Relay LoRA workflow +- [G2D (arXiv 2506.21514)](https://arxiv.org/abs/2506.21514) — Sequential Modality Prioritization inspiration for modality freezing +- [UniAVGen (arXiv 2511.03334)](https://arxiv.org/abs/2511.03334) — Joint audio-video generation reference for lower-LR AV training guidance +- [Harmony (arXiv 2511.21579)](https://arxiv.org/abs/2511.21579) — Cross-Task Synergy; basis for `--cts_lambda_video_driven` and `--cts_lambda_audio_driven` + +**LTX Resources** +- [LTX-2](https://github.com/Lightricks/LTX-2) — LTX-2/2.3 model and pipeline resources +- [LTX-Video](https://github.com/Lightricks/LTX-Video) — LTX model resources, inference tooling, ComfyUI nodes, and model weights +- [LTX Documentation](https://docs.ltx.video/open-source-model/getting-started/overview) — Unified docs hub: open-source model, API reference, ComfyUI integration, LoRA usage, and LTX-2 trainer guide + +**Alternative Trainers** +- [ai-toolkit](https://github.com/ostris/ai-toolkit) (ostris) — General diffusion fine-tuning toolkit with LTX-2/2.3 LoRA support; slider LoRA training is based on its implementation +- [diffusion-pipe](https://github.com/tdrussell/diffusion-pipe) — Pipeline-parallel diffusion model trainer with LTX-Video and LTX 2.3 support; initial LTX 2.3 support covers T2I/T2V training, without audio +- [DiffSynth-Studio](https://github.com/modelscope/DiffSynth-Studio) — ModelScope diffusion synthesis framework with LTX-2/2.3 support +- [SimpleTuner](https://github.com/bghira/SimpleTuner) — Multi-model fine-tuning framework with LTX-2/2.3 support; `--crepa backbone` mode is inspired by its LayerSync regularizer + +**Community Resources** +- [awesome-ltx2](https://github.com/wildminder/awesome-ltx2) — Curated list of LTX-2 resources, tools, models, and guides +- [Banodoco Discord](https://discord.gg/SrkBPTzw) — Active AI video generation community; discussions on LTX-2 training, workflows, and research +- [Windows Installation Guide](https://github.com/AkaneTendo25/musubi-tuner/discussions/19) — Windows-specific setup (Python 3.12, CUDA, Flash Attention 2), dependencies, troubleshooting +- [LTX-2 Training Optimizers](https://github.com/AkaneTendo25/musubi-tuner/discussions/21) — Optimizer comparison for LTX-2 training: AdamW, Prodigy, Muon, CAME, and recommended settings +- [LTX-2 Audio Dataset Builder](https://github.com/dorpxam/LTX-2-Audio-Dataset-Builder) — Tool to automate audio dataset creation: transforms raw audio into clean, captioned segments optimized for LTX-2 audio-only training + +**Tutorials & Guides** +- [LTX-2 LoRA Training Complete Guide](https://apatero.com/blog/ltx-2-lora-training-fine-tuning-complete-guide-2025) (Apatero) — Dataset preparation, training configuration, and LoRA deployment walkthrough +- [How to Train a LTX-2 Character LoRA](https://ghost.oxen.ai/how-to-train-a-ltx-2-character-lora-with-oxen-ai/) (Oxen.ai) — Character-consistency LoRA training with dataset prep tips for audio clips + +**Cloud Platforms** +- [fal.ai LTX-2 Trainer](https://fal.ai/models/fal-ai/ltx2-video-trainer) — Cloud-based LTX-2 LoRA training via API (~$0.005/step) +- [WaveSpeedAI LTX-2](https://wavespeed.ai/landing/ltx2) — Hosted LTX-2 inference (T2V, I2V, video extend, lipsync) + diff --git a/VRGDG_Musubi-tuner/docs/qinglong_distribution.png b/VRGDG_Musubi-tuner/docs/qinglong_distribution.png new file mode 100644 index 0000000000000000000000000000000000000000..862b9eab5a8e52d87cd6fd68468e2fccb678ae31 --- /dev/null +++ b/VRGDG_Musubi-tuner/docs/qinglong_distribution.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0b63e0ff906e6a28d178ac12c29112741e0d5527d38c9940533713bcd64e0dd5 +size 15478 diff --git a/VRGDG_Musubi-tuner/docs/qwen_image.md b/VRGDG_Musubi-tuner/docs/qwen_image.md new file mode 100644 index 0000000000000000000000000000000000000000..124a93233d21a1822fabafe736fe49db202b3dd9 --- /dev/null +++ b/VRGDG_Musubi-tuner/docs/qwen_image.md @@ -0,0 +1,618 @@ +# Qwen-Image + +## Overview / 概要 + +This document describes the usage of the Qwen-Image and Qwen-Image-Edit/Edit-2509/Edit-2511/Layered architecture within the Musubi Tuner framework. Qwen-Image is a text-to-image generation model that supports standard text-to-image generation, and Qwen-Image-Edit is a model that supports image editing with control images, Layered is a model that supports image layer segmentation. + +Qwen-Image-Edit-2509/2511 can use multiple control images simultaneously. While the official version supports up to 3 images, Musubi Tuner allows specifying any number of images (though correct operation is confirmed only up to 3). Additionally, the sizes of the control images can differ (both during training and inference). + +This feature is experimental. + +Latent pre-caching, training, and inference options can be found in the `--help` output. Many options are shared with HunyuanVideo, so refer to the [HunyuanVideo documentation](./hunyuan_video.md) as needed. + +
+日本語 + +このドキュメントは、Musubi Tunerフレームワーク内でのQwen-Image、Qwen-Image-Edit/Edit-2509/Edit-2511/Layeredアーキテクチャの使用法について説明しています。Qwen-Imageは標準的なテキストから画像生成モデルで、Qwen-Image-Editは制御画像を使った画像編集をサポートするモデル、Layeredは画像のレイヤー分割をサポートするモデルです。 + +Qwen-Image-Edit-2509/2511は、複数枚の制御画像を同時に使用できます。公式では3枚までですが、Musubi Tunerでは任意の枚数を指定できます(正しく動作するのは3枚までです)。またそれぞれの制御画像のサイズは異なっていても問題ありません(学習時、推論時とも)。 + +この機能は実験的なものです。 + +事前キャッシング、学習、推論のオプションは`--help`で確認してください。HunyuanVideoと共通のオプションが多くありますので、必要に応じて[HunyuanVideoのドキュメント](./hunyuan_video.md)も参照してください。 + +
+ +## Download the model / モデルのダウンロード + +You need to download the DiT, VAE, and Text Encoder (Qwen2.5-VL) models. + +Official weights from [Qwen's official weights](https://huggingface.co/Qwen) can be used for DiT, Text Encoder, and VAE respectively. If you want to use the weights for ComfyUI, please follow below. + +- **Qwen-Image DiT, Text Encoder (Qwen2.5-VL)**: For Qwen-Image DiT and Text Encoder, download `split_files/diffusion_models/qwen_image_bf16.safetensors` and `split_files/text_encoders/qwen_2.5_vl_7b.safetensors` from https://huggingface.co/Comfy-Org/Qwen-Image_ComfyUI, respectively. **The fp8_scaled version cannot be used.** + +- **VAE**: For VAE, download `split_files/vae/qwen_image_vae.safetensors` similarly from https://huggingface.co/Comfy-Org/Qwen-Image-Edit_ComfyUI. ComfyUI's VAE weights are also now usable. + +- **Qwen-Image-Edit DiT**: For Qwen-Image-Edit DiT, download `split_files/diffusion_models/qwen_image_edit_bf16.safetensors`, or for Edit-2509, download `split_files/diffusion_models/qwen_image_edit_2509_bf16.safetensors`, and for Edit-2511, download similar from https://huggingface.co/Comfy-Org/Qwen-Image-Edit_ComfyUI. **fp8_e4m3fn cannot be used.** Text Encoder and VAE are same as Qwen-Image. + +- **Qwen-Image-Layered VAE**: For Qwen-Image-Layered VAE, download `split_files/vae/qwen_image_layered_vae.safetensors` from https://huggingface.co/Comfy-Org/Qwen-Image-Layered_ComfyUI. + +- **Qwen-Image-Layered DiT**: For Qwen-Image-Layered DiT, download `split_files/diffusion_models/qwen_image_layered_bf16.safetensors` from https://huggingface.co/Comfy-Org/Qwen-Image-Layered_ComfyUI. **fp8mixed cannot be used.** Text Encoder is same as Qwen-Image. + +Thanks to Comfy-Org for releasing these weights. + +
+日本語 + +DiT, VAE, Text Encoder (Qwen2.5-VL) のモデルをダウンロードする必要があります。 + +DiT、Text Encoder、VAEのそれぞれに、[Qwenの公式の重み](https://huggingface.co/Qwen)を使用可能です。ComfyUI用の重みを使用する場合は、以下の通りです。 +- **DiT, Text Encoder (Qwen2.5-VL)**: DiTおよびText Encoderは、`split_files/diffusion_models/qwen_image_bf16.safetensors` と `split_files/text_encoders/qwen_2.5_vl_7b.safetensors` を https://huggingface.co/Comfy-Org/Qwen-Image_ComfyUI からそれぞれダウンロードしてください。**fp8_scaledバージョンは使用できません。** + +- **VAE**: VAEは `split_files/vae/qwen_image_vae.safetensors` を同様に https://huggingface.co/Comfy-Org/Qwen-Image-Edit_ComfyUI からダウンロードしてください。ComfyUIのVAEの重みも使用できるようになりました。 + +- **Qwen-Image-Edit DiT**: Qwen-Image-Edit DiTは、`split_files/diffusion_models/qwen_image_edit_bf16.safetensors` を、Edit-2509の場合は `split_files/diffusion_models/qwen_image_edit_2509_bf16.safetensors` を https://huggingface.co/Comfy-Org/Qwen-Image-Edit_ComfyUI からダウンロードしてください。**`fp8_e4m3fn`は使用できません。**Text EncoderとVAEはQwen-Imageと同じです。 + +これらの重みを公開してくださったComfy-Orgに感謝します。 + +
+ +### Summary of files to download / ダウンロードするファイルのまとめ + +**fp8_scaled and fp8_e4m3fn versions cannot be used.** + +**Download from https://huggingface.co/Comfy-Org/Qwen-Image_ComfyUI :** +|type|model|file| +|----|--------|--------------| +|DiT|Qwen-Image (no edit)|`split_files/diffusion_models/qwen_image_bf16.safetensors`| +|Text Encoder|Qwen2.5-VL|`split_files/text_encoders/qwen_2.5_vl_7b.safetensors`| +|VAE|Qwen-Image VAE|`split_files/vae/qwen_image_vae.safetensors`| + +**Download from https://huggingface.co/Comfy-Org/Qwen-Image-Edit_ComfyUI :** +|type|model|file| +|----|--------|--------------| +|DiT|Qwen-Image-Edit|`split_files/diffusion_models/qwen_image_edit_bf16.safetensors`| +|DiT|Qwen-Image-Edit-2509|`split_files/diffusion_models/qwen_image_edit_2509_bf16.safetensors`| +|DiT|Qwen-Image-Edit-2511|`split_files/diffusion_models/qwen_image_edit_2511_bf16.safetensors`| + +**Download from https://huggingface.co/Comfy-Org/Qwen-Image-Layered_ComfyUI :** +|type|model|file| +|----|--------|--------------| +|VAE|Qwen-Image-Layered VAE|`split_files/vae/qwen_image_layered_vae.safetensors`| +|DiT|Qwen-Image-Layered|`split_files/diffusion_models/qwen_image_layered_bf16.safetensors`| + + +## Specifying Model Version / モデルバージョンの指定 + +When specifying the model version in various scripts, use the following options: +|type|option|note| +|----|--------|----| +|Qwen-Image|`--model_version original`|default, can be omitted| +|Qwen-Image-Edit|`--model_version edit`| | +|Qwen-Image-Edit-2509|`--model_version edit-2509`| | +|Qwen-Image-Edit-2511|`--model_version edit-2511`| | +|Qwen-Image-Layered|`--model_version layered`| | + +Note that the `--edit` (for Qwen-Image-Edit) and `--edit_plus` (for Qwen-Image-Edit-2509) flags are also available for backward compatibility. + +
+日本語 + +様々なスクリプトでモデルバージョンを指定する際には、英語版の表を参考にしてください。 + +`--edit`(Qwen-Image-Edit)および`--edit_plus`(Qwen-Image-Edit-2509)フラグも後方互換性のために利用可能です。 + +
+ +## Pre-caching / 事前キャッシング + +If you are using Qwen-Image-Edit or Edit-2509/2511, please also refer to the [Qwen-Image-Edit section](./dataset_config.md#qwen-image-edit-and-qwen-image-edit-2509) of the dataset config documentation. + +If you are using Qwen-Image-Layered, note the following: Since the Qwen-Image-Layered dataset contains multiple target images, please specify `multiple_target=true` in the dataset config. For details, refer to the [dataset config document](./dataset_config.md#sample-for-image-dataset-with-caption-text-files). + + +### Latent Pre-caching / latentの事前キャッシング + +Latent pre-caching uses a dedicated script for Qwen-Image. + +```bash +python src/musubi_tuner/qwen_image_cache_latents.py \ + --dataset_config path/to/toml \ + --vae path/to/vae_model \ + --model_version original +``` + +- Uses `qwen_image_cache_latents.py`. +- The `--vae` argument is required. +- Use the `--model_version` option for Qwen-Image-Edit/Layered training. +- For Qwen-Image-Edit training, control images specified in the dataset config will also be cached as latents. +- For Qwen-Image-Layered training, multiple target images will be cached as latents + +
+日本語 + +Qwen-Image-EditまたはEdit-2509/2511を使用する場合は、事前にデータセット設定のドキュメントの[Qwen-Image-Editのセクション](./dataset_config.md#qwen-image-edit-and-qwen-image-edit-2509) も参照してください。 + +Qwen-Image-Layeredを使用する場合は、以下に注意してください。Qwen-Image-Layeredのデータセットには複数枚のターゲット画像が含まれるため、データセット設定で`multiple_target=true`を指定してください。詳細は[データセット設定ドキュメント](./dataset_config.md#sample-for-image-dataset-with-caption-text-files)を参照してください。 + +latentの事前キャッシングはQwen-Image専用のスクリプトを使用します。 + +- `qwen_image_cache_latents.py`を使用します。 +- `--vae`引数を指定してください。 +- Qwen-Image-Editの学習には`--model_version`オプションを適切に指定してください。 +- Qwen-Image-Editの学習では、データセット設定で指定されたコントロール画像もlatentsとしてキャッシュされます +- Layeredの学習では、複数のターゲット画像がlatentsとしてキャッシュされます。 + +
+ +### Text Encoder Output Pre-caching / テキストエンコーダー出力の事前キャッシング + +Text encoder output pre-caching also uses a dedicated script. + +```bash +python src/musubi_tuner/qwen_image_cache_text_encoder_outputs.py \ + --dataset_config path/to/toml \ + --text_encoder path/to/text_encoder \ + --batch_size 1 \ + --model_version original +``` + +- Uses `qwen_image_cache_text_encoder_outputs.py`. +- Requires the `--text_encoder` (Qwen2.5-VL) argument. +- Use the `--fp8_vl` option to run the Text Encoder in fp8 mode for VRAM savings for <16GB GPUs. +- Specify `--model_version` for Qwen-Image-Edit training. Prompts will be processed with control images to generate appropriate embeddings. + +**Technical details on the difference between `--model_version edit` and `--model_version edit-2509` and `--model_version edit-2511`** + +Qwen-Image-Edit-2509 and 2511 can use multiple images as control images, so the prompts for obtaining Text Encoder outputs differ from Edit. + +
+日本語 + +テキストエンコーダー出力の事前キャッシングも専用のスクリプトを使用します。 + +- `qwen_image_cache_text_encoder_outputs.py`を使用します。 +- `--text_encoder` (Qwen2.5-VL) 引数が必要です。 +- VRAMを節約するために、fp8 でテキストエンコーダを実行する`--fp8_vl`オプションが使用可能です。VRAMが16GB未満のGPU向けです。 +- Qwen-Image-Editの学習には`--model_version`を指定してください。プロンプトがコントロール画像と一緒に処理され、適切な埋め込みが生成されます。 + +**`--model_version edit`と`--model_version edit-2509`および`--model_version edit-2511`の違いに関する技術的詳細** + +Qwen-Image-Edit-2509および2511では複数枚の画像をコントロール画像として使用できるため、Text Encoder出力の取得のためのプロンプトがEditとは異なります。 + +
+ +## LoRA Training / LoRA学習 + +Training uses a dedicated script `qwen_image_train_network.py`. + +**Standard Qwen-Image Training:** + +```bash +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 src/musubi_tuner/qwen_image_train_network.py \ + --dit path/to/dit_model \ + --vae path/to/vae_model \ + --text_encoder path/to/text_encoder \ + --model_version original \ + --dataset_config path/to/toml \ + --sdpa --mixed_precision bf16 \ + --timestep_sampling shift \ + --weighting_scheme none --discrete_flow_shift 2.2 \ + --optimizer_type adamw8bit --learning_rate 5e-5 --gradient_checkpointing \ + --max_data_loader_n_workers 2 --persistent_data_loader_workers \ + --network_module networks.lora_qwen_image \ + --network_dim 16 \ + --max_train_epochs 16 --save_every_n_epochs 1 --seed 42 \ + --output_dir path/to/output_dir --output_name name-of-lora +``` + +**Qwen-Image-Edit Training:** + +For training the image editing model, add the `--model_version` option for Qwen-Image-Edit, Edit-2509, or Edit-2511. + +```bash +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 src/musubi_tuner/qwen_image_train_network.py \ + --dit path/to/edit_dit_model \ + --vae path/to/vae_model \ + --text_encoder path/to/text_encoder \ + --dataset_config path/to/toml \ + --model_version edit-2511 \ + ... +``` + +**Qwen-Image-Layered Training:** + +For training Qwen-Image-Layered models with layered control images, add the `--model_version layered` option. + +`--remove_first_image_from_target` option is also available to exclude the first target image from the model input/target during training. The first image among multiple target images inferred by the official model in Qwen-Image-Layered is the original image, and the rest are layer images. By using this option, you can train only on the layer images without inferring the original image. This improves training and inference speed and reduces memory usage. The impact on quality is unknown. + +Note that VAE is different for this architecture. Please use the VAE model for Qwen-Image-Layered. + +For sample image generation during Qwen-Image-Layered training, please refer to [this document](./sampling_during_training.md#sample-image-generation-during-qwen-image-layered-training--qwen-image-layeredの学習中のサンプルイメージ生成). + +--- + +Common notes for Qwen-Image/Qwen-Image-Edit/Layered training: + +- Uses `qwen_image_train_network.py`. +- **Requires** specifying `--dit`, `--vae`, and `--text_encoder`. +- `--mixed_precision bf16` is recommended for Qwen-Image training. +- Use the `--model_version` option for Qwen-Image-Edit, Edit-2509, or Edit-2511 training with control images, or for Qwen-Image-Layered training with multiple target images. +- Memory saving options like `--fp8_base` and `--fp8_scaled` (for DiT), and `--fp8_vl` (for Text Encoder) are available. +- `--gradient_checkpointing` and `--gradient_checkpointing_cpu_offload` are available for memory savings. See [HunyuanVideo documentation](./hunyuan_video.md#memory-optimization) for details. +- `--disable_numpy_memmap`: Disables numpy memory mapping for model loading, loading with standard file read. Increases RAM usage but significantly speeds up model loading in some cases. + +`--fp8_vl` is recommended for GPUs with less than 16GB of VRAM. + +`--sdpa` uses PyTorch's scaled dot product attention. Other options like `--xformers` and `--flash_attn` are available. `flash3` cannot be used currently. + +If you specify `--split_attn`, the attention computation will be split, slightly reducing memory usage. Please specify `--split_attn` if you are using anything other than `--sdpa`. + +`--timestep_sampling` allows you to choose the sampling method for the timesteps. `shift` with `--discrete_flow_shift` is the default. `qwen_shift` is also available. `qwen_shift` is a same method during inference. It uses the dynamic shift value based on the resolution of each image (typically around 2.2 for 1328x1328 images). + +`--discrete_flow_shift` is set quite low for Qwen-Image during inference (as described), so a lower value than other models may be preferable. + +Don't forget to specify `--network_module networks.lora_qwen_image`. + +The appropriate settings for each parameter are unknown. Feedback is welcome. + +### VRAM Usage Estimates with Memory Saving Options + +For 1024x1024 training with the batch size of 1, `--mixed_precision bf16` and `--gradient_checkpointing` is enabled and `--xformers` is used. + +|options|VRAM Usage| +|-------|----------| +|no |42GB| +|`--fp8_base --fp8_scaled`|30GB| +|+ `--blocks_to_swap 16`|24GB| +|+ `--blocks_to_swap 45`|12GB| + +64GB main RAM system is recommended with `--blocks_to_swap`. + +If `--blocks_to_swap` is more than 45, the main RAM usage will increase significantly. + +Qwen-Image-Edit training requires additional memory for the control images. + +**Note:** The `--disable_numpy_memmap` option speeds up model loading in some cases with using standard file read instead of using numpy memory mapping. If you encounter slow model weight loading time, this option may help. + +
+日本語 + +Qwen-Imageの学習は専用のスクリプト`qwen_image_train_network.py`を使用します。コマンドライン例は英語版を参照してください。 + +**Qwen-Image-Editの学習について** + +画像編集モデルの学習には、Qwen-Image-Edit、Edit-2509、またはEdit-2511の`--model_version`オプションを追加してください。 + +**Qwen-Image-Layeredの学習について** + +レイヤード制御画像を使用したQwen-Image-Layeredモデルの学習には、`--model_version layered`オプションを追加してください。 + +`--remove_first_image_from_target`オプションも利用可能で、学習中に最初のターゲット画像をモデルの入力/ターゲットから除外します。Qwen-Image-Layeredでは公式モデルでは推論される複数枚の画像のうち、最初の画像は元の画像であり、残りがレイヤー画像となっています。このオプションを使用すると、元の画像を推論せずにレイヤー画像のみを学習できます。これにより学習、推論の速度が向上し、メモリ使用量も削減されます。品質への影響は不明です。 + +このアーキテクチャではVAEが異なることに注意してください。Qwen-Image-Layered用のVAEモデルを使用してください。 + +Qwen-Image-Layeredにおける学習中のサンプル画像生成については、[こちらのドキュメント](./sampling_during_training.md#sample-image-generation-during-qwen-image-layered-training--qwen-image-layeredの学習中のサンプルイメージ生成)を参照してください。 + +--- + +Qwen-Image/Edit/Layered学習に共通の注意点: + +- `qwen_image_train_network.py`を使用します。 +- `--dit`、`--vae`、`--text_encoder`を指定する必要があります。 +- Qwen-Imageの学習には`--mixed_precision bf16`を推奨します。 +- コントロール画像を使ったQwen-Image-Edit/Edit-2509/Edit-2511の学習、複数ターゲット画像を使ったQwen-Image-Layeredの学習には、`--model_version`オプションを適切に指定してください。 +- `--fp8_base`や`--fp8_scaled`(DiT用)、`--fp8_vl`(テキストエンコーダー用)などのメモリ節約オプションが利用可能です。 +- メモリ節約のために`--gradient_checkpointing`が利用可能です。 +- `--disable_numpy_memmap`: モデル読み込み時のnumpyメモリマッピングを無効化し、標準のファイル読み込みで読み込みを行います。RAM使用量は増加しますが、場合によってはモデルの読み込みが大幅に高速化されます。もしモデルの重みの読み込み時間が遅い場合は、このオプションが役立つかもしれません。 + +GPUのVRAMが16GB未満の場合は、`--fp8_vl`を推奨します。 + +`--sdpa`はPyTorchのscaled dot product attentionを用います。他に `--xformers`、`--flash_attn` があります。`--flash3`は現在使用できません。 + +`--split_attn` を指定すると、attentionの計算が分割され、メモリ使用量がわずかに削減されます。`--sdpa` 以外を使用する場合は、`--split_attn` を指定してください。 + +`--timestep_sampling` では、タイムステップのサンプリング方法を選択できます。`shift` と `--discrete_flow_shift` の組み合わせがデフォルトです。`qwen_shift` も利用可能です。`qwen_shift` は推論時と同じ方法で、各画像の解像度に基づいた動的シフト値を使用します(通常、1328x1328画像の場合は約2.2です)。 + +`--discrete_flow_shift`は、Qwen-Imageでは前述のように推論時にかなり低めなため、他のモデルよりも低めが良いかもしれません。 + +`--network_module networks.lora_qwen_image`を指定することを忘れないでください。 + +それぞれのパラメータの適切な設定は不明です。フィードバックをお待ちしています。 + +### メモリ節約オプションを使用した場合のVRAM使用量の目安 + +1024x1024の学習でバッチサイズ1の場合、`--mixed_precision bf16`と`--gradient_checkpointing`を指定し、`--xformers`を使用した場合のVRAM使用量の目安は以下の通りです。 + +|オプション|VRAM使用量| +|-------|----------| +|no |42GB| +|`--fp8_base --fp8_scaled`|30GB| +|+ `--blocks_to_swap 16`|24GB| +|+ `--blocks_to_swap 45`|12GB| + +`--blocks_to_swap`を使用する場合は、64GBのメインRAMを推奨します。 + +`--blocks_to_swap`が45を超えると、メインRAMの使用量が大幅に増加します。 + +Qwen-Image-Editの学習では、コントロール画像のために追加のメモリが必要です。 + +**備考:** `--disable_numpy_memmap`オプションは、numpyメモリマッピングの代わりに標準のファイル読み込みを使用することで、場合によってはモデルの読み込みを高速化します。モデルの重みの読み込み時間が遅い場合は、このオプションが役立つかもしれません。 + +
+ +## Finetuning + +Finetuning uses a dedicated script `qwen_image_train.py`. This script performs full finetuning of the model, not LoRA. Sample usage is as follows: + +```bash +accelerate launch --num_cpu_threads_per_process 1 src/musubi_tuner/qwen_image_train.py \ + --dit path/to/dit_model \ + --vae path/to/vae_model \ + --text_encoder path/to/text_encoder \ + --model_version original \ + --dataset_config path/to/toml \ + --sdpa --mixed_precision bf16 --gradient_checkpointing \ + --optimizer_type adafactor --learning_rate 1e-6 --fused_backward_pass \ + --optimizer_args "relative_step=False" "scale_parameter=False" "warmup_init=False" \ + --max_grad_norm 0 --lr_scheduler constant_with_warmup --lr_warmup_steps 10 \ + --max_data_loader_n_workers 2 --persistent_data_loader_workers \ + --max_train_epochs 16 --save_every_n_epochs 1 --seed 42 \ + --output_dir path/to/output_dir --output_name name-of-model +``` + +- Uses `qwen_image_train.py`. +- Finetuning requires a large amount of VRAM. The use of memory saving options is strongly recommended. +- `--full_bf16`: Loads the model weights in bfloat16 format to significantly reduce VRAM usage. +- `--optimizer_type adafactor`: Using Adafactor is recommended for finetuning. +- `--fused_backward_pass`: Reduces VRAM usage during the backward pass when using Adafactor. +- `--mem_eff_save`: Reduces main memory (RAM) usage when saving checkpoints. +- `--blocks_to_swap`: Swaps model blocks between VRAM and main memory to reduce VRAM usage. This is effective when VRAM is limited. +- `--disable_numpy_memmap`: Disables numpy memory mapping for model loading, loading with standard file read. Increases RAM usage but may speed up model loading in some cases. + +`--full_bf16` reduces VRAM usage by about 20GB but may impact model accuracy as the weights are kept in bfloat16. Note that the optimizer state is still kept in float32. In addition, it is recommended to use this with an optimizer that supports stochastic rounding. In this repository, Adafactor optimizer with `--fused_backward_pass` option supports stochastic rounding. + +When using `--mem_eff_save`, please note that traditional saving methods are still used when saving the optimizer state in `--save_state`, requiring about 40GB of main memory. + +`--model_version` option allows for finetuning of Qwen-Image-Edit/Edit-2509/Edit-2511 (unverified). + +### Recommended Settings + +We are still exploring the optimal settings. The configurations above are just examples, so please adjust them as needed. We welcome your feedback. + +If you have ample VRAM, you can use any optimizer of your choice. `--full_bf16` is not recommended. + +For limited VRAM environments (e.g., 48GB or less), you may need to use `--full_bf16`, the Adafactor optimizer, and `--fused_backward_pass`. Settings above are the recommended options for that case. Please adjust `--lr_warmup_steps` to a value between approximately 10 and 100. + +`--fused_backward_pass` is not currently compatible with gradient accumulation, and max grad norm may not function as expected, so it is recommended to specify `--max_grad_norm 0`. + +If your VRAM is even more constrained, you can enable block swapping by specifying a value for `--blocks_to_swap`. + +Experience with other models suggests that the learning rate may need to be reduced significantly; something in the range of 1e-6 to 1e-5 might be a good place to start. + +
+日本語 + +Finetuningは専用のスクリプト`qwen_image_train.py`を使用します。このスクリプトはLoRAではなく、モデル全体のfinetuningを行います。 + +- `qwen_image_train.py`を使用します。 +- Finetuningは大量のVRAMを必要とします。メモリ節約オプションの使用を強く推奨します。 +- `--full_bf16`: モデルの重みをbfloat16形式で読み込み、VRAM使用量を大幅に削減します。 +- `--optimizer_type adafactor`: FinetuningではAdafactorの使用が推奨されます。 +- `--fused_backward_pass`: Adafactor使用時に、backward pass中のVRAM使用量を削減します。 +- `--mem_eff_save`: チェックポイント保存時のメインメモリ(RAM)使用量を削減します。 +- `--blocks_to_swap`: モデルのブロックをVRAMとメインメモリ間でスワップし、VRAM使用量を削減します。VRAMが少ない場合に有効です。 +- `--disable_numpy_memmap`: モデル読み込み時のnumpyメモリマッピングを無効化し、標準のファイル読み込みで読み込みを行います。RAM使用量は増加しますが、場合によってはモデルの読み込みが高速化されます。 + +`--full_bf16`はVRAM使用量を約20GB削減しますが、重みがbfloat16で保持されるため、モデルの精度に影響を与える可能性があります。オプティマイザの状態はfloat32で保持されます。また、効率的な学習のために、stochastic roundingをサポートするオプティマイザとの併用が推奨されます。このリポジトリでは、`adafactor`オプティマイザに`--fused_backward_pass`オプションの組み合わせでstochastic roundingをサポートしています。 + +`--mem_eff_save`を使用する場合でも、`--save_state`においてはオプティマイザの状態を保存する際に従来の保存方法が依然として使用されるため、約40GBのメインメモリが必要であることに注意してください。 + +`--model_version`オプションにより、Qwen-Image-Edit/Edit-2509/Edit-2511のfinetuningが可能です(未検証)。 + +### 推奨設定 + +最適な設定はまだ調査中です。上記の構成はあくまで一例ですので、必要に応じて調整してください。フィードバックをお待ちしております。 + +十分なVRAMがある場合は、お好みのオプティマイザを使用できます。`--full_bf16`は推奨されません。 + +VRAMが限られている環境(例:48GB以下)の場合は、`--full_bf16`、Adafactorオプティマイザ、および`--fused_backward_pass`を使用する必要があるかもしれません。上記の設定はその場合の推奨オプションです。`--lr_warmup_steps`は約10から100の間の値に調整してください。 + +現時点では`--fused_backward_pass`はgradient accumulationに対応していません。またmax grad normも想定通りに動作しない可能性があるため、`--max_grad_norm 0`を指定することを推奨します。 + +さらにVRAMが制約されている場合は、`--blocks_to_swap`に値を指定してブロックスワッピングを有効にできます。 + +
+ +## Inference / 推論 + +Inference uses a dedicated script `qwen_image_generate_image.py`. + +**Standard Qwen-Image Inference:** + +```bash +python src/musubi_tuner/qwen_image_generate_image.py \ + --dit path/to/dit_model \ + --vae path/to/vae_model \ + --text_encoder path/to/text_encoder \ + --prompt "A cat" \ + --negative_prompt " " \ + --image_size 1024 1024 --infer_steps 25 \ + --guidance_scale 4.0 \ + --attn_mode sdpa \ + --save_path path/to/save/dir \ + --output_type images \ + --seed 1234 --lora_multiplier 1.0 --lora_weight path/to/lora.safetensors +``` + +**Qwen-Image-Edit Inference:** + +```bash +python src/musubi_tuner/qwen_image_generate_image.py \ + --dit path/to/edit_dit_model \ + --vae path/to/vae_model \ + --text_encoder path/to/text_encoder \ + --model_version edit-2511 \ + --control_image_path path/to/control_image.png \ + --prompt "Change the background to a beach" \ + --resize_control_to_official_size \ + ... +``` + +**Qwen-Image-Layered Inference:** + +Please specify `--model_version layered` for Qwen-Image-Layered inference. Note that VAE is different for this architecture. Please use the VAE model for Qwen-Image-Layered. + +--- + +- Uses `qwen_image_generate_image.py`. +- **Requires** specifying `--dit`, `--vae`, and `--text_encoder`. +- `--image_size` is the size of the generated image, height and width are specified in that order. +- `--prompt`: Prompt for generation. +- `--guidance_scale` controls the classifier-free guidance scale. +- For Qwen-Image-Edit: + - Use the `--model_version` option to specify the version for image editing mode. For example, `--model_version edit-2511` or `--model_version layered`. + - `--control_image_path`: Path to the control (reference) image for editing. Edit-2509 also supports multiple arguments (e.g., `--control_image_path img1.png img2.png img3.png`). + - `--resize_control_to_image_size`: Resize control image to match the specified image size. + - `--resize_control_to_official_size`: Resize control image to official size (1M pixels keeping aspect ratio). **Recommended for better results with Edit models.** (Mandatory for 2511) + - Above two options are mutually exclusive. If both are not specified, the control image will be used at its original resolution. + - `--append_original_name`: When saving edited images, appends the original base name of the control image to the output file name. +- For Qwen-Image-Layered: + - Specify the image to be layered in `--control_image_path`. + - Specify the number of layers to output in `--output_layers`. (Since Qwen-Image-Layered also generates the original image, it generates one more than the specified number. If `--remove_first_image_from_target` was used during training, specify "the number of layers - 1" here to match the number of generated images.) + - `--resize_control_to_image_size`: Resize control image to match the specified image size. **Recommended for better results with Layered models.** +- Memory saving options like `--fp8_scaled` (for DiT) are available. +- `--text_encoder_cpu` enables CPU inference for the text encoder. Recommended for systems with limited GPU resources (less than 16GB VRAM). +- LoRA loading options (`--lora_weight`, `--lora_multiplier`) are available. + +You can specify the discrete flow shift using `--flow_shift`. If omitted, the default value (dynamic shifting based on the image size) will be used. + +`xformers`, `flash` and `sageattn` are also available as attention modes. However `sageattn` is not confirmed to work yet. + +
+日本語 + +Qwen-Imageの推論は専用のスクリプト`qwen_image_generate_image.py`を使用します。コマンド例は英語版のドキュメントを参照してください。 + +**Qwen-Image-Layeredの推論について** + +Qwen-Image-Layeredの推論には`--model_version layered`を指定してください。このアーキテクチャではVAEが異なることに注意してください。Qwen-Image-Layered用のVAEモデルを使用してください。 + +--- + +- `qwen_image_generate_image.py`を使用します。 +- `--dit`、`--vae`、`--text_encoder`を指定する必要があります。 +- `--image_size`は生成する画像のサイズで、高さと幅をその順番で指定します。 +- `--prompt`: 生成用のプロンプトです。 +- `--guidance_scale`は、classifier-freeガイダンスのスケールを制御します。 +- Qwen-Image-Editの場合: + - 画像編集モードを有効にするために`--model_version`オプションを適切に指定してください。 + - `--control_image_path`: 編集用のコントロール(参照)画像へのパスです。 Edit-2509では複数の引数もサポートしています(例: `--control_image_path img1.png img2.png img3.png`)。 + - `--resize_control_to_image_size`: コントロール画像を指定した画像サイズに合わせてリサイズします。 + - `--resize_control_to_official_size`: コントロール画像を公式サイズ(アスペクト比を保ちながら100万ピクセル)にリサイズします。指定を推奨します(特に2511では必須)。 + - 上記2つのオプションは同時に指定できません。両方とも指定しない場合、制御画像はそのままの解像度で使用されます。 + - `--append_original_name`: 編集された画像を保存する際に、コントロール画像の元の基本名を出力ファイル名に追加します。 +- Qwen-Image-Layeredの場合: + - `--control_image_path`に、分割対象の画像を指定してください。 + - `--output_layers`に出力するレイヤー数を指定してください。(Qwen-Image-Layeredは元画像も生成するため、指定した数より1枚多く生成されます。もし学習時に`--remove_first_image_from_target`を使用していた場合は、ここには「レイヤー数-1」を指定してください。) + - `--resize_control_to_image_size`: コントロール画像を指定した画像サイズに合わせてリサイズします。Layeredモデルでより良い結果を得るために推奨されます。 +- DiTのメモリ使用量を削減するために、`--fp8_scaled`オプションを指定可能です。 +- `--text_encoder_cpu`を指定するとテキストエンコーダーをCPUで推論します。GPUのVRAMが16GB未満のシステムでは、CPU推論を推奨します。 +- LoRAの読み込みオプション(`--lora_weight`、`--lora_multiplier`)が利用可能です。 + +`--flow_shift`を指定することで、離散フローシフトを設定できます。省略すると、デフォルト値(画像サイズに基づく動的シフト)が使用されます。 + +`xformers`、`flash`、`sageattn`もattentionモードとして利用可能です。ただし、`sageattn`はまだ動作確認が取れていません。 + +
+ +### Inpainting and Reference Consistency Mask (RCM) + +For Qwen-Image-Edit, inpainting with a mask image and a feature called Reference Consistency Mask (RCM) are available to prevent unintended changes in the background or other areas. + +**These features are only available in Edit/Edit-plus mode, and require the first control image to be the same size as the output image.** They cannot be used at the same time. + +- `--mask_path`: Specifies the path to a mask image for inpainting. The image should be black and white, where white areas indicate the regions to be inpainted (changed) and black areas indicate the regions to be preserved. +- `--rcm_threshold`: Enables the Reference Consistency Mask (RCM) feature. RCM is a technique that dynamically creates a mask during the denoising process to prevent unintended modifications to areas that should remain unchanged. It compares the latents of the current generation step with the latents of the control image and protects areas with small differences. Lower values for the threshold result in a larger inpainting area. Typical values are 0.01 to 0.1 for absolute threshold, 0.1 to 0.5 for relative threshold. +- `--rcm_relative_threshold`: If this flag is set, the `--rcm_threshold` is treated as a relative value (0.0-1.0) to the maximum difference observed in the current step. This can provide more stable results across different steps. If not set, the threshold is an absolute value. +- `--rcm_kernel_size`: Specifies the kernel size for a Gaussian blur applied before calculating the difference. This helps to create a smoother, more stable mask. Default is 3. +- `--rcm_dilate_size`: Specifies the size to dilate (expand) the inpainting region of the generated mask. This is useful for ensuring that the edges of the area you want to change are properly modified. Default is 0 (no dilation). +- `--rcm_debug_save`: When this flag is set, the dynamically generated RCM mask for each step will be saved in the output directory. This is very useful for debugging and adjusting the RCM parameters. + +**Example using RCM:** + +```bash +python src/musubi_tuner/qwen_image_generate_image.py \ + --dit path/to/edit_dit_model \ + --vae path/to/vae_model \ + --text_encoder path/to/text_encoder \ + --edit \ + --control_image_path path/to/control_image.png \ + --prompt "Change her dress to red" \ + --image_size 1024 1024 \ + --rcm_threshold 0.2 --rcm_relative_threshold \ + --rcm_kernel_size 3 --rcm_dilate_size 1 \ + ... +``` + +#### Important Usage Notes + +- **Compatibility:** Both RCM and the standard inpainting mask are only effective in **edit mode** (when a control image is provided). +- **Requirement:** To use these features, the initial control image must have the **same dimensions** as the final output image. The script will show an error and disable RCM if the sizes do not match. +- **Exclusivity:** RCM and `--mask_path` cannot be used at the same time. +- **Debugging Tip:** When first using RCM, it is highly recommended to use the `--rcm_debug_save` flag. This will save the masks to the output directory, allowing you to visually inspect how the `threshold` and other parameters are affecting the mask generation. + +#### Technical Details of RCM + +Reference Consistency Mask (RCM) addresses a common issue in Qwen-Image-Edit where the generated image has a slight positional drift or misalignment compared to the control image. RCM significantly improves the structural stability and positional accuracy of the image editing process. + +This feature is implemented based on the idea of dynamically creating a mask during the denoising loop to "anchor" the parts of the image that should remain consistent with the reference (control) image. + +**How RCM Works** + +For each step in the denoising loop, RCM performs the following actions: +1. It calculates a "noisy" version of the original control latent, corresponding to the current timestep `t`. +2. It computes the difference between the current generation latent and the noisy control latent. +3. Areas with a small difference are considered "consistent" and are masked to be preserved. The sensitivity is controlled by the `rcm_threshold`. +4. This mask is then used to reset the consistent regions of the current latent back to the state of the noisy reference latent, just before the `scheduler.step` is called. + +This self-correcting mechanism prevents the accumulation of positional errors throughout the denoising process, ensuring that unchanged elements like backgrounds or faces stay perfectly aligned. + +
+日本語 + +Qwen-Image-Editにおいて、背景などを意図せず変更してしまうことを防ぐため、マスク画像を使ったInpaintingと、Reference Consistency Mask (RCM) という機能が利用可能です。 + +**これらの機能はEdit/Edit-plusモードでのみ利用可能で、かつ最初のコントロール画像が出力画像と同じサイズである必要があります。** また、同時に使用することはできません。 + +- `--mask_path`: Inpainting用のマスク画像へのパスを指定します。白黒のマスク画像で、白の領域がInpainting(変更)される領域、黒の領域が維持される領域を示します。 +- `--rcm_threshold`: Reference Consistency Mask (RCM) 機能を有効にします。RCMは、Denoisingの過程で動的にマスクを生成し、変更すべきでない箇所が意図せず変更されるのを防ぐ技術です。現在の生成ステップのlatentとコントロール画像のlatentを比較し、差が小さい部分を保護します。閾値が低いほど、Inpainting領域は大きくなります。 +- `--rcm_relative_threshold`: このフラグを指定すると、`--rcm_threshold`がそのステップで観測された差分の最大値に対する相対的な値(0.0~1.0)として扱われます。これにより、ステップごとに安定した結果が得られやすくなります。指定しない場合は絶対値として扱われます。絶対値の場合は0.01~0.1、相対値の場合は0.1~0.5が典型的な値です。 +- `--rcm_kernel_size`: 差分を計算する前に適用するガウシアンブラーのカーネルサイズを指定します。これにより、より滑らかで安定したマスクが生成されます。デフォルトは3です。 +- `--rcm_dilate_size`: 生成されたマスクのInpainting領域を膨張(dilate)させるサイズを指定します。変更したい領域の境界部分が確実に変更されるようにしたい場合に便利です。デフォルトは0(膨張なし)です。 +- `--rcm_debug_save`: このフラグを指定すると、各ステップで動的に生成されたRCMのマスクが出力ディレクトリに保存されます。RCMのパラメータを調整する際のデバッグに非常に役立ちます。 + +**重要な使用上の注意** + +- **互換性:** RCMと標準のinpaintingマスクは、どちらも**Editモード**(制御画像が提供されている場合)でのみ有効です。 +- **要件:** これらの機能を使用するには、最初の制御画像が最終的な出力画像と**同じサイズ**である必要があります。サイズが一致しない場合、スクリプトはエラーを表示し、RCMを無効にします。 +- **排他性:** RCMと`--mask_path`は同時に使用できません。 +- **デバッグのヒント:** 初めてRCMを使用する際は、`--rcm_debug_save`フラグを使用することを強く推奨します。これによりマスクが出力ディレクトリに保存され、`threshold`などのパラメータがマスク生成にどのように影響しているかを視覚的に確認できます。 + +**RCMの技術的詳細** + +Reference Consistency Mask (RCM) は、Qwen-Image-Editにおいて、生成画像が制御画像と比較してわずかな位置ずれを起こすという一般的な問題を解決するためのものです。RCMは、編集プロセスにおける構造的な安定性と位置精度を大幅に向上させます。 + +この機能は、denoisingループ中に動的にマスクを生成し、参照元(制御画像)と一致すべき部分を「固定(アンカー)」するというアイデアに基づいています。 + +**RCMの動作原理** + +RCMは、denoisingループの各ステップで以下の処理を実行します。 +1. 現在のタイムステップ`t`に対応する、元の制御画像の潜在変数にノイズを加えたバージョンを計算します。 +2. 現在の生成中latentと、ノイズ付加済み制御latentとの差分を計算します。 +3. 差分が小さい領域を「一致している」とみなし、その部分を保持するようにマスクします。この感度は`rcm_threshold`によって制御されます。 +4. そして、このマスクを使い、`scheduler.step`が呼び出される直前に、一致している領域をノイズ付加済み参照latentの状態にリセットします。 + +この自己修正的なメカニズムにより、denoisingプロセス全体を通して位置誤差が蓄積されるのを防ぎ、背景や顔のような変更しない要素が完全に位置ずれなく維持されることを保証します。 + +
\ No newline at end of file diff --git a/VRGDG_Musubi-tuner/docs/sampling_during_training.md b/VRGDG_Musubi-tuner/docs/sampling_during_training.md new file mode 100644 index 0000000000000000000000000000000000000000..e79fa78cd49bb71d85bcc3bc5e84c554e6c29cdc --- /dev/null +++ b/VRGDG_Musubi-tuner/docs/sampling_during_training.md @@ -0,0 +1,141 @@ +> 📝 Click on the language section to expand / 言語をクリックして展開 + +# Sampling during training / 学習中のサンプル画像生成 + +By preparing a prompt file, you can generate sample images during training. + +Please be aware that it consumes a considerable amount of VRAM, so be careful when generating sample images for videos with a large number of frames. Also, since it takes time to generate, adjust the frequency of sample image generation as needed. + +
+日本語 + +プロンプトファイルを用意することで、学習中にサンプル画像を生成することができます。 + +VRAMをそれなりに消費しますので、特にフレーム数が多い動画を生成する場合は注意してください。また生成には時間がかかりますので、サンプル画像生成の頻度は適宜調整してください。 +
+ +## How to use / 使い方 + +### Command line options for training with sampling / サンプル画像生成に関連する学習時のコマンドラインオプション + +Example of command line options for training with sampling / 記述例: + +```bash +--vae path/to/ckpts/hunyuan-video-t2v-720p/vae/pytorch_model.pt +--vae_chunk_size 32 --vae_spatial_tile_sample_min_size 128 +--text_encoder1 path/to/ckpts/text_encoder +--text_encoder2 path/to/ckpts/text_encoder_2 +--sample_prompts /path/to/prompt_file.txt +--sample_every_n_epochs 1 --sample_every_n_steps 1000 --sample_at_first +``` + +`--vae`, `--vae_chunk_size`, `--vae_spatial_tile_sample_min_size`, `--text_encoder1`, `--text_encoder2` are the same as when generating images, so please refer to [here](/README.md#inference) for details. `--fp8_llm` can also be specified. + +`--sample_prompts` specifies the path to the prompt file used for sample image generation. Details are described below. + +`--sample_every_n_epochs` specifies how often to generate sample images in epochs, and `--sample_every_n_steps` specifies how often to generate sample images in steps. + +`--sample_at_first` is specified when generating sample images at the beginning of training. + +Sample images and videos are saved in the `sample` directory in the directory specified by `--output_dir`. They are saved as `.png` for still images and `.mp4` for videos. + +
+日本語 + +`--vae`、`--vae_chunk_size`、`--vae_spatial_tile_sample_min_size`、`--text_encoder1`、`--text_encoder2`は、画像生成時と同様ですので、詳細は[こちら](/README.ja.md#推論)を参照してください。`--fp8_llm`も指定可能です。 + +`--sample_prompts`は、サンプル画像生成に使用するプロンプトファイルのパスを指定します。詳細は後述します。 + +`--sample_every_n_epochs`は、何エポックごとにサンプル画像を生成するかを、`--sample_every_n_steps`は、何ステップごとにサンプル画像を生成するかを指定します。 + +`--sample_at_first`は、学習開始時にサンプル画像を生成する場合に指定します。 + +サンプル画像、動画は、`--output_dir`で指定したディレクトリ内の、`sample`ディレクトリに保存されます。静止画の場合は`.png`、動画の場合は`.mp4`で保存されます。 +
+ +### Prompt file / プロンプトファイル + +The prompt file is a text file that contains the prompts for generating sample images. The example is as follows. / プロンプトファイルは、サンプル画像生成のためのプロンプトを記述したテキストファイルです。例は以下の通りです。 + +``` +# prompt 1: for generating a cat video +A cat walks on the grass, realistic style. --w 640 --h 480 --f 25 --d 1 --s 20 + +# prompt 2: for generating a dog image +A dog runs on the beach, realistic style. --w 960 --h 544 --f 1 --d 2 --s 20 +``` + +A line starting with `#` is a comment. + +* `--w` specifies the width of the generated image or video. The default is 256. +* `--h` specifies the height. The default is 256. +* `--f` specifies the number of frames. The default is 1, which generates a still image. +* `--d` specifies the seed. The default is random. +* `--s` specifies the number of steps in generation. The default is 20. +* `--g` specifies the embedded guidance scale (not CFG scale). The default is 6.0 for HunyuanVideo, 10.0 for FramePack, 2.5 for FLUX.1 Kontext which is the default value during inference of each architecture. Specify 1.0 for SkyReels V1 models. Ignore this option for Wan2.1 models. +* `--fs` specifies the discrete flow shift. The default is 14.5, which corresponds to the number of steps 20. In the HunyuanVideo paper, 7.0 is recommended for 50 steps, and 17.0 is recommended for less than 20 steps (e.g. 10). Ignore this option for FramePack models (it uses 10.0). Set 0 to use 'flux_shift' for FLUX.1 Kontext models. + +If you train I2V models, you must add the following option. + +* `--i path/to/image.png`: the image path for image2video inference. PNG, JPG and other formats are supported. + +If you train Wan2.1-Fun-Control models, you must add the following option. + +* `--cn path/to/control_video_or_dir_of_images`: the path to the video or directory containing multiple images for control. + +If you train the model with classifier free guidance (such as Wan2.1), you can use the additional options below. + +*`--n negative prompt...`: the negative prompt for the classifier free guidance. The default prompt for each model is used if omitted. +*`--l 6.0`: the classifier free guidance scale. Should be set to 6.0 for SkyReels V1 models. 5.0 is the default value for Wan2.1 (if omitted). + +If you train the model with control images (such as FramePack one frame inference or FLUX.1 Kontext), you can use the additional options below. + +* `--ci path/to/control_image.jpg`: the control image path for inference. If you specify this option, the control image is used for inference. PNG, JPG and other formats are supported. + +### Sample image generation during Qwen-Image-Layered training / Qwen-Image-Layeredの学習中のサンプルイメージ生成 + +`--f` option is treated as the number of output layers. + +The prompt can be omitted when generating sample images during Qwen-Image-Layered training. In this case, the prompt is generated based on the control image by Qwen2.5-VL. + +※ Since Qwen-Image-Layered models generate "original image + multiple layer images", the number of images generated is the number specified by the `--f` option + 1. The second and subsequent images are separated layer images. + +
+日本語 + +`#` で始まる行はコメントです。 + +* `--w` 生成画像、動画の幅を指定します。省略時は256です。 +* `--h` 高さを指定します。省略時は256です。 +* `--f` フレーム数を指定します。省略時は1で、静止画を生成します。 +* `--d` シードを指定します。省略時はランダムです。 +* `--s` 生成におけるステップ数を指定します。省略時は20です。 +* `--g` embedded guidance scaleを指定します(CFG scaleではありません)。省略時はHunyuanVideoは6.0、FramePackは10.0で、各アーキテクチャの推論時のデフォルト値です。SkyReels V1モデルの場合は1.0を指定してください。FLUX.1 Kontextの場合は2.5を指定してください。Wan2.1モデルの場合はこのオプションは無視されます。 +* `--fs` discrete flow shiftを指定します。省略時は14.5で、ステップ数20の場合に対応した値です。HunyuanVideoの論文では、ステップ数50の場合は7.0、ステップ数20未満(10など)で17.0が推奨されています。FramePackモデルはこのオプションは無視され、10.0が使用されます。FLUX.1 Kontextモデルでは、0を指定すると `flux_shift` が使用されます。 + +I2Vモデルを学習する場合、以下のオプションを追加してください。 + +* `--i path/to/image.png`: image2video推論用の画像パス。PNG、JPGなどの形式がサポートされています。 + +Wan2.1-Fun-Controlモデルを学習する場合、以下のオプションを追加してください。 + +* `--cn path/to/control_video_or_dir_of_images`: control用の動画または複数枚の画像を含むディレクトリのパス。 + +classifier free guidance(ネガティブプロンプト)を必要とするモデル(Wan2.1など)を学習する場合、以下の追加オプションを使用できます。 + +*`--n negative prompt...`: classifier free guidance用のネガティブプロンプト。省略時はモデルごとのデフォルトプロンプトが使用されます。 +*`--l 6.0`: classifier free guidance scale。SkyReels V1モデルの場合は6.0に設定してください。Wan2.1の場合はデフォルト値が5.0です(省略時)。 + +制御画像を使用するモデル(FramePackの1フレーム推論やFLUX.1 Kontextなど)を学習する場合、以下の追加オプションを使用できます。 + +* `--ci path/to/control_image.jpg`: 推論用の制御画像パス。このオプションを指定すると、制御画像が推論に使用されます。PNG、JPGなどの形式がサポートされています。 + +**Qwen-Image-Layeredの学習中のサンプルイメージ生成** + +`--f`オプションが出力レイヤー数として扱われます。 + +Qwen-Image-Layeredの学習中にサンプル画像を生成する際、プロンプトは省略可能です。この場合、プロンプトはQwen2.5-VLによってコントロール画像に基づいて生成されます。 + +※ Qwen-Image-Layeredモデルは「元画像+複数のレイヤー画像」を生成するため、`--f`オプションで指定した数+1枚の画像が生成されます。2枚目以降が分離されたレイヤー画像です。 + +
diff --git a/VRGDG_Musubi-tuner/docs/shift_3.png b/VRGDG_Musubi-tuner/docs/shift_3.png new file mode 100644 index 0000000000000000000000000000000000000000..3826ea32bc3e624f3b278c16355d2e6eaee3c7c2 --- /dev/null +++ b/VRGDG_Musubi-tuner/docs/shift_3.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9ae14ecf6f5c991ff137eed71d4cb56c4a98d8f18621ebe41c385077957546a6 +size 13957 diff --git a/VRGDG_Musubi-tuner/docs/shift_3_500_1000.png b/VRGDG_Musubi-tuner/docs/shift_3_500_1000.png new file mode 100644 index 0000000000000000000000000000000000000000..91e27da16f12e0bd874be10da2702a14f87ad82d --- /dev/null +++ b/VRGDG_Musubi-tuner/docs/shift_3_500_1000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:03603c5b4b5e643824e42f3eb23e44261f0b6cf717b38a1d564e37d4c992b8d8 +size 13204 diff --git a/VRGDG_Musubi-tuner/docs/shift_3_500_1000_preserve.png b/VRGDG_Musubi-tuner/docs/shift_3_500_1000_preserve.png new file mode 100644 index 0000000000000000000000000000000000000000..717e453b9e5e7724cd7ace83039da4b63c89f89f --- /dev/null +++ b/VRGDG_Musubi-tuner/docs/shift_3_500_1000_preserve.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:10d8e1c6095ad6725ef5f05107b43bdf8b94c6c2e5e03d1d32e55a8253f59452 +size 14196 diff --git a/VRGDG_Musubi-tuner/docs/tools.md b/VRGDG_Musubi-tuner/docs/tools.md new file mode 100644 index 0000000000000000000000000000000000000000..1e6b3724b0dbd4c7750572cd3d19c5c989422c24 --- /dev/null +++ b/VRGDG_Musubi-tuner/docs/tools.md @@ -0,0 +1,406 @@ +> 📝 Click on the language section to expand / 言語をクリックして展開 + +# Tools + +This document provides documentation for utility tools available in this project. + +## Table of Contents + +- [LoRA Post-Hoc EMA merging / LoRAのPost-Hoc EMAマージ](#lora-post-hoc-ema-merging--loraのpost-hoc-emaマージ) +- [Image Captioning with Qwen2.5-VL / Qwen2.5-VLによる画像キャプション生成](#image-captioning-with-qwen25-vl--qwen25-vlによる画像キャプション生成) + +## 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: + +```bash +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: +```bash +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: +```bash +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`: +```bash +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](./betas_for_sigma_rel.png) + +### 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マージは独立したスクリプトとして提供されています: + +```bash +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 + チェックポイントファイルのソートを無効にする(指定した順序でマージ) +``` + +### 例: + +定数減衰率での基本的な使用法: +```bash +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つの減衰率間の線形補間を使用: +```bash +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: +```bash +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精度で計算されます。保存時は元のデータ型が維持されます + +
+ +## Image Captioning with Qwen2.5-VL / Qwen2.5-VLによる画像キャプション生成 + +The `caption_images_by_qwen_vl.py` script automatically generates captions for a directory of images using a fine-tuned Qwen2.5-VL model. It's designed to help prepare datasets for training by creating captions from the images themselves. + +The Qwen2.5-VL model used in Qwen-Image is not confirmed to be the same as the original Qwen2.5-VL-Instruct model, but it appears to work for caption generation based on the tests conducted. + +
+日本語 + +`caption_images_by_qwen_vl.py`スクリプトは、Qwen2.5-VLモデルを使用して、指定されたディレクトリ内の画像に対するキャプションを自動生成します。画像自体からキャプションを作成することで、学習用データセットの準備を支援することを目的としています。 + +Qwen-Imageで使用されているQwen2.5-VLモデルは、元のQwen2.5-VL-Instructモデルと同じかどうか不明ですが、試した範囲ではキャプション生成も動作するようです。 + +
+ +### Arguments + +- `--image_dir` (required): Path to the directory containing the images to be captioned. +- `--model_path` (required): Path to the Qwen2.5-VL model. See [here](./qwen_image.md#download-the-model--モデルのダウンロード) for instructions. +- `--output_file` (optional): Path to the output JSONL file. This is required if `--output_format` is `jsonl`. +- `--max_new_tokens` (optional, default: 1024): The maximum number of new tokens to generate for each caption. +- `--prompt` (optional, default: see script): A custom prompt to use for caption generation. You can use `\n` for newlines. +- `--max_size` (optional, default: 1280): The maximum size of the image. Images are resized to fit within a `max_size` x `max_size` area while maintaining aspect ratio. +- `--fp8_vl` (optional, flag): If specified, the Qwen2.5-VL model is loaded in fp8 precision for lower memory usage. +- `--output_format` (optional, default: `jsonl`): The output format. Can be `jsonl` to save all captions in a single JSONL file, or `text` to save a separate `.txt` file for each image. + +`--max_size` can be reduced to decrease the image size passed to the VLM. This can reduce the memory usage of the VLM, but may also decrease the quality of the generated captions. + +The default prompt is defined in the [source file](/src/musubi_tuner/caption_images_by_qwen_vl.py). It is based on the [Qwen-Image Technical Report](https://arxiv.org/abs/2508.02324). + +
+日本語 + +- `--image_dir` (必須): キャプションを生成する画像が含まれるディレクトリへのパス。 +- `--model_path` (必須): Qwen2.5-VLモデルへのパス。詳細は[こちら](./qwen_image.md#download-the-model--モデルのダウンロード)を参照してください。 +- `--output_file` (任意): 出力先のJSONLファイルへのパス。`--output_format`が`jsonl`の場合に必須です。 +- `--max_new_tokens` (任意, デフォルト: 1024): 各キャプションで生成する新しいトークンの最大数。 +- `--prompt` (任意, デフォルト: スクリプト内参照): キャプション生成に使用するカスタムプロンプト。`\n`で改行を指定できます。 +- `--max_size` (任意, デフォルト: 1280): 画像の最大サイズ。アスペクト比を維持したまま、画像の合計ピクセル数が`max_size` x `max_size`の領域に収まるようにリサイズされます。 +- `--fp8_vl` (任意, フラグ): 指定された場合、Qwen2.5-VLモデルがfp8精度で読み込まれ、メモリ使用量が削減されます。 +- `--output_format` (任意, デフォルト: `jsonl`): 出力形式。`jsonl`を指定するとすべてのキャプションが単一のJSONLファイルに保存され、`text`を指定すると画像ごとに個別の`.txt`ファイルが保存されます。 + +`--max_size` を小さくするとVLMに渡される画像サイズが小さくなります。これにより、VLMのメモリ使用量が削減されますが、生成されるキャプションの品質が低下する可能性があります。 + +プロンプトのデフォルトは、[ソースファイル](/src/musubi_tuner/caption_images_by_qwen_vl.py)内で定義されています。[Qwen-Image Technical Report](https://arxiv.org/abs/2508.02324)を参考にしたものです。 + +
+ +### Usage Examples + +**1. Basic Usage (JSONL Output)** + +```bash +python src/musubi_tuner/caption_images_by_qwen_vl.py \ + --image_dir /path/to/images \ + --model_path /path/to/qwen_model.safetensors \ + --output_file /path/to/captions.jsonl +``` + +**2. Text File Output** + +This will create a `.txt` file with the same name as each image in the `/path/to/images` directory. + +```bash +python src/musubi_tuner/caption_images_by_qwen_vl.py \ + --image_dir /path/to/images \ + --model_path /path/to/qwen_model.safetensors \ + --output_format text +``` + +**3. Advanced Usage (fp8, Custom Prompt, and Max Size)** + +```bash +python src/musubi_tuner/caption_images_by_qwen_vl.py \ + --image_dir /path/to/images \ + --model_path /path/to/qwen_model.safetensors \ + --output_file /path/to/captions.jsonl \ + --fp8_vl \ + --max_size 1024 \ + --prompt "A detailed and descriptive caption for this image is:\n" +``` diff --git a/VRGDG_Musubi-tuner/docs/torch_compile.md b/VRGDG_Musubi-tuner/docs/torch_compile.md new file mode 100644 index 0000000000000000000000000000000000000000..7a940321b1f7ca52d60dc9eec6f1b17ab075906c --- /dev/null +++ b/VRGDG_Musubi-tuner/docs/torch_compile.md @@ -0,0 +1,399 @@ +# torch.compile Support + +## Overview / 概要 + +This document describes the `torch.compile` optimization feature in Musubi Tuner. PyTorch's `torch.compile` is a just-in-time (JIT) compilation feature that can significantly improve training and inference performance by optimizing model execution. + +For technical details and implementation specifics, please refer to [Pull Request #722](https://github.com/kohya-ss/musubi-tuner/pull/722). + +Also, refer to the official PyTorch documentation: https://docs.pytorch.org/tutorials/intermediate/torch_compile_tutorial.html#introduction-to-torch-compile + +Note: `torch.compile` may not work well in various situations. Please refer to the "Limitations and Known Issues" section below for details. If it does not work, please use the traditional method for training/inference. + +
+日本語 + +このドキュメントでは、Musubi Tunerにおける`torch.compile`最適化機能について説明します。PyTorchの`torch.compile`は、モデルの実行を最適化することで学習と推論のパフォーマンスを大幅に向上させることができるジャストインタイム(JIT)コンパイル機能です。 + +技術的な詳細や実装の詳細については、[Pull Request #722](https://github.com/kohya-ss/musubi-tuner/pull/722)を参照してください。 + +PyTorchの公式ドキュメントも参照してください: https://docs.pytorch.org/tutorials/intermediate/torch_compile_tutorial.html#introduction-to-torch-compile + +※ `torch.compile`は様々な要因でうまく動作しない場合があります。詳細は以下の「制限事項と既知の問題」セクションを参照してください。また動作しない場合には従来の方法での学習/推論を行ってください。 + +
+ +### Prerequisites / 前提条件 + +- triton is required for `torch.compile` to work effectively. For Windows, see [triton-windows repository](https://github.com/woct0rdho/triton-windows) for installation instructions. +- MSVC compiler is required on Windows for `--compile_dynamic` option. Visual Studio 2022 with C++ development tools or Visual Studio Build Tools 2022 is recommended. See [Windows Requirements for `--compile_dynamic`](#windows-requirements-for---compile_dynamic--windowsでの---compile_dynamic-の要件). + +
+日本語 + +- `torch.compile`を効果的に動作させるにはtritonが必要です。Windowsの場合、インストール手順については[triton-windowsリポジトリ](https://github.com/woct0rdho/triton-windows)を参照してください。 +- Windowsで`--compile_dynamic`オプションを使用するにはMSVCコンパイラが必要です。Visual Studio 2022のC++開発ツールまたはVisual Studio Build Tools 2022の使用を推奨します。[`--compile_dynamic`のWindows要件](#windows-requirements-for---compile_dynamic--windowsでの---compile_dynamic-の要件)を参照してください。 + +
+ +### Performance Improvements / パフォーマンス向上 + +The performance gains vary depending on hardware and settings. Here are some examples: + +**Qwen-Image, 1328×1328, BS1: RTX A6000, Power Limit 180W, Windows:** +- Default mode: ~10.5% faster +- max-autotune-no-cudagraphs: ~11.1% faster + +**RTX PRO 6000 Blackwell, Power Limit 250W, Windows:** +- Default mode: ~18.8% faster +- max-autotune-no-cudagraphs: ~25.2% faster + +
+日本語 + +パフォーマンス向上は、ハードウェアと設定によって異なります。以下は一例です: + +**Qwen-Image, 1328×1328, BS1: RTX A6000, Power Limit 180W, Windows:** +- デフォルトモード: 約10.5%高速化 +- max-autotune-no-cudagraphs: 約11.1%高速化 + +**RTX PRO 6000 Blackwell, Power Limit 250W, Windows:** +- デフォルトモード: 約18.8%高速化 +- max-autotune-no-cudagraphs: 約25.2%高速化 + +
+ +## Supported Architectures / サポートされているアーキテクチャ + +`torch.compile` is supported for both training and inference in the following architectures: + +- HunyuanVideo +- Wan2.1/2.2 +- FramePack +- FLUX.1 Kontext +- Qwen-Image / Qwen-Image-Edit / Qwen-Image-Edit-2509 + +
+日本語 + +以下のアーキテクチャで、学習と推論の両方において`torch.compile`がサポートされています: + +- HunyuanVideo +- Wan2.1/2.2 +- FramePack +- FLUX.1 Kontext +- Qwen-Image / Qwen-Image-Edit / Qwen-Image-Edit-2509 + +
+ +## Command Line Arguments / コマンドライン引数 + +### Basic Arguments / 基本的な引数 + +- `--compile`: Enable torch.compile optimization +- `--compile_backend`: Backend to use (default: `inductor`) +- `--compile_mode`: Compilation mode (default: `default` for training, `max-autotune-no-cudagraphs` for inference) + - Choices: `default`, `reduce-overhead`, `max-autotune`, `max-autotune-no-cudagraphs` +- `--compile_dynamic`: Enable dynamic shapes support (default is None, equivalent to `auto`) (Requires Visual Studio 2022 C++ compiler on Windows) + - Choices: `true`, `false`, `auto` +- `--compile_fullgraph`: Enable fullgraph mode +- `--compile_cache_size_limit`: Set cache size limit (default: PyTorch default, typically 8-32, recommended: 32) + +So far, it has been observed that setting `compile_mode` to `max-autotune` may not work in some cases. +Also, `compile_fullgraph` may not work depending on the architecture. + +If `compile_dynamic` is not set to `true`, recompilation will occur each time the shape of the model input changes. This may result in longer training times for the first epoch, but subsequent epochs will be faster. + +### Additional Performance Arguments / 追加のパフォーマンス引数 + +- `--cuda_allow_tf32`: Allow TF32 precision on Ampere or newer GPUs (improves performance) +- `--cuda_cudnn_benchmark`: Enable cuDNN benchmark mode (may improve performance) + +
+日本語 + +### 基本的な引数 + +- `--compile`: torch.compile最適化を有効にする +- `--compile_backend`: 使用するバックエンド(デフォルト: `inductor`) +- `--compile_mode`: コンパイルモード(デフォルト: 学習時は`default`、推論時は`max-autotune-no-cudagraphs`) + - 選択肢: `default`, `reduce-overhead`, `max-autotune`, `max-autotune-no-cudagraphs` +- `--compile_dynamic`: 動的形状サポートを指定する(デフォルトは None で `auto` 相当)(Windows環境ではVisual Studio 2022のC++コンパイラが必要) + - 選択肢: `true`, `false`, `auto` +- `--compile_fullgraph`: フルグラフモードを有効にする +- `--compile_cache_size_limit`: キャッシュサイズ制限を設定(デフォルト: PyTorchのデフォルト、通常8-32、推奨: 32) + +これまでに確認したところ、`compile_mode`は`max-autotune`に設定すると動作しないケースがあるようです。 +また、`compile_fullgraph`はアーキテクチャにより動作しない場合があります。 + +`compile_dynamic`で `true` を指定しない場合、モデルの入力の形状が変わるごとに再コンパイルが発生します。最初のエポックの学習時間が長くなる可能性がありますが、その後のエポックでは高速化されます。 + +### 追加のパフォーマンス引数 + +- `--cuda_allow_tf32`: Ampereまたはそれ以降のGPUでTF32精度を許可する(パフォーマンス向上) +- `--cuda_cudnn_benchmark`: cuDNNベンチマークモードを有効にする(パフォーマンスが向上する可能性がある) + +
+ +## Usage Examples / 使用例 + +### Training / 学習 + +#### Basic Usage / 基本的な使い方 + +```bash +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 \ + src/musubi_tuner/qwen_image_train_network.py \ + --dit path/to/dit \ + --dataset_config path/to/config.toml \ + (... other args ...) \ + --compile \ + --compile_cache_size_limit 32 +``` + +※ Windows Command Prompt users should use ^ at the end of lines. + +#### Advanced Usage / 高度な使い方 + +```bash +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 \ + src/musubi_tuner/hv_train_network.py \ + --dit path/to/dit \ + --dataset_config path/to/config.toml \ + (... other args ...) \ + --compile \ + --compile_mode max-autotune-no-cudagraphs \ + --compile_cache_size_limit 32 \ + --cuda_allow_tf32 \ + --cuda_cudnn_benchmark +``` + +
+日本語 + +### 学習 + +#### 基本的な使い方 + +```bash +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 \ + src/musubi_tuner/qwen_image_train_network.py \ + --dit path/to/dit \ + --dataset_config path/to/config.toml \ + (... その他の引数 ...) \ + --compile \ + --compile_cache_size_limit 32 +``` + +※ Windowsでコマンドプロンプトを使用する場合、末尾は ^ を使用してください。 + +#### 高度な使い方 + +```bash +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 \ + src/musubi_tuner/hv_train_network.py \ + --dit path/to/dit \ + --dataset_config path/to/config.toml \ + (... その他の引数 ...) \ + --compile \ + --compile_mode max-autotune-no-cudagraphs \ + --compile_cache_size_limit 32 \ + --cuda_allow_tf32 \ + --cuda_cudnn_benchmark +``` + +
+ +### Inference / 推論 + +```bash +python src/musubi_tuner/qwen_image_generate_image.py \ + --dit path/to/dit \ + --vae path/to/vae \ + --text_encoder path/to/text_encoder \ + --prompt "A beautiful landscape" \ + --compile \ + --compile_mode max-autotune-no-cudagraphs +``` + +The existing `--compile_args` option is deprecated. It is still available for now but will be removed in the future. Please use the new individual arguments as shown in the example above. + +
+日本語 + +### 推論 + +```bash +python src/musubi_tuner/qwen_image_generate_image.py \ + --dit path/to/dit \ + --vae path/to/vae \ + --text_encoder path/to/text_encoder \ + --prompt "A beautiful landscape" \ + --compile \ + --compile_mode max-autotune-no-cudagraphs +``` + +既存の `--compile_args` オプションは非推奨となりました。現時点では使用可能ですが、将来的には削除される予定です。上の使用例のように、新しい個別の引数を使用してください。 + +
+ +## Limitations and Known Issues / 制限事項と既知の問題 + +### Incompatible Options and Constraints / 互換性のないオプションと制約 + +- **`--compile_fullgraph` and `--split_attn`**: These options cannot be used together. The `--split_attn` option uses dynamic control flow that is incompatible with fullgraph mode. +- **`--blocks_to_swap`**: When using block swapping, `torch.compile` automatically disables compilation for Linear layers in swapped blocks to avoid conflicts. This may limit performance improvements. + +### Windows Requirements for `--compile_dynamic` / Windowsでの `--compile_dynamic` の要件 + +**IMPORTANT**: On Windows, using `--compile_dynamic` requires: + +1. **Visual Studio 2022** with C++ development tools installed +2. Either: + - Running the training/inference script from **"x64 Native Tools Command Prompt for VS 2022"** + - Running the training/inference script after setting environment variables by executing `vcvars64.bat` located in the Visual Studio installation directory. For example: `"C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\Build\vcvars64.bat"` + +If you encounter compilation errors when using `--compile_dynamic` on Windows, make sure you are running from the correct command prompt. + + + +
+日本語 + +**互換性のないオプションと制約** + +- **`--compile_fullgraph` と `--split_attn`**: これらのオプションは同時に使用できません。`--split_attn`オプションは動的な制御フローを使用しており、フルグラフモードと互換性がありません。 +- **`--blocks_to_swap`**: ブロックスワッピングを使用する場合、`torch.compile`は衝突を避けるため、スワップされるブロック内のLinearレイヤーのコンパイルを自動的に無効にします。そのため、速度向上が制限される可能性があります。 + +**Windowsでの `--compile_dynamic` の要件** + +**重要**: Windowsで`--compile_dynamic`を使用する場合、以下が必要です: + +1. **Visual Studio 2022** とC++開発ツールのインストール +2. 以下のいずれか: + - **"x64 Native Tools Command Prompt for VS 2022"** からのスクリプト実行 + - vcvars64.batを実行して環境変数を設定した後にスクリプトを実行:Visual Studioのインストールディレクトリにある`vcvars64.bat`を実行して環境変数を設定します。例: `"C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\Build\vcvars64.bat"` + +Windowsで`--compile_dynamic`を使用してコンパイルエラーが発生する場合は、正しい手順でコマンドプロンプトから実行していることを確認してください。 + +PyTorchの以下の公式ドキュメントも参照してください: https://docs.pytorch.org/tutorials/unstable/inductor_windows.html#install-a-compiler + +
+ +## Recommended Settings / 推奨設定 + +### For Training / 学習向け + +```bash +--compile \ +--compile_mode default \ +--compile_cache_size_limit 32 \ +--cuda_allow_tf32 \ +--cuda_cudnn_benchmark +``` + +### For Inference / 推論向け + +```bash +--compile \ +--compile_mode max-autotune-no-cudagraphs \ +--compile_cache_size_limit 32 +``` + +
+日本語 + +### 学習向け + +```bash +--compile \ +--compile_mode default \ +--compile_cache_size_limit 32 \ +--cuda_allow_tf32 \ +--cuda_cudnn_benchmark +``` + +### 推論向け + +```bash +--compile \ +--compile_mode max-autotune-no-cudagraphs \ +--compile_cache_size_limit 32 +``` + +
+ +## Compilation Modes / コンパイルモード + +- **`default`**: Balanced compilation with good performance and reasonable compile times. Recommended for training. +- **`reduce-overhead`**: Reduces Python overhead, useful for small models or frequent small operations. +- **`max-autotune`**: Maximum optimization with longer compile times. May provide best performance but increases initial compilation time. May not work on some architectures. +- **`max-autotune-no-cudagraphs`**: Similar to max-autotune but without CUDA graphs. Recommended for inference as it provides good performance improvements with better compatibility. + +
+日本語 + +- **`default`**: バランスの取れたコンパイルで、適切なパフォーマンスと合理的なコンパイル時間を提供します。学習に推奨されます。 +- **`reduce-overhead`**: Pythonのオーバーヘッドを削減します。小さなモデルや頻繁な小規模操作に有用です。 +- **`max-autotune`**: コンパイル時間は長くなりますが、最大限の最適化を行います。最高のパフォーマンスを提供する可能性がありますが、初期コンパイル時間が増加します。アーキテクチャによっては動作しない場合があります。 +- **`max-autotune-no-cudagraphs`**: max-autotuneと似ていますが、CUDAグラフを使用しません。良好な互換性で優れたパフォーマンス向上を提供するため、推論に推奨されます。 + +
+ +## Troubleshooting / トラブルシューティング + +### First Iteration is Slow + +This is expected behavior. `torch.compile` performs JIT compilation on the first forward pass, which takes extra time. Subsequent iterations will be much faster. + +### Out of Memory Errors + +If you encounter out-of-memory errors when using `torch.compile`, try: +- Using a smaller `--compile_cache_size_limit` value +- Reducing batch size +- Using `--compile_mode default` instead of `max-autotune` + +### Compilation Errors on Windows + +If using `--compile_dynamic` on Windows and encountering compilation errors: +1. Ensure Visual Studio 2022 with C++ development tools is installed +2. Run the script from "x64 Native Tools Command Prompt for VS 2022" +3. If issues persist, try without `--compile_dynamic` + +
+日本語 + +**最初のイテレーションが遅い** + +これは予想される動作です。`torch.compile`は最初のforward passでJITコンパイルを実行するため、追加の時間がかかります。その後のイテレーションははるかに高速になります。 + +**メモリ不足エラー** + +`torch.compile`を使用してメモリ不足エラーが発生する場合は、次を試してください: +- より小さな`--compile_cache_size_limit`値を使用する +- バッチサイズを減らす +- `max-autotune`の代わりに`--compile_mode default`を使用する + +**Windowsでのコンパイルエラー** + +Windowsで`--compile_dynamic`を使用してコンパイルエラーが発生する場合: +1. C++開発ツールを含むVisual Studio 2022がインストールされていることを確認する +2. "x64 Native Tools Command Prompt for VS 2022"からスクリプトを実行する +3. 問題が解決しない場合は、`--compile_dynamic`なしで試す + +
+ +## Additional Resources / 追加リソース + +- [PyTorch torch.compile documentation](https://docs.pytorch.org/tutorials/intermediate/torch_compile_tutorial.html) +- [PyTorch Inductor Windows documentation](https://docs.pytorch.org/tutorials/unstable/inductor_windows.html) +- [Pull Request #722](https://github.com/kohya-ss/musubi-tuner/pull/722) - Technical implementation details + +
+日本語 + +- [PyTorch torch.compile ドキュメント](https://docs.pytorch.org/tutorials/intermediate/torch_compile_tutorial.html) +- [PyTorch Inductor Windows ドキュメント](https://docs.pytorch.org/tutorials/unstable/inductor_windows.html) +- [Pull Request #722](https://github.com/kohya-ss/musubi-tuner/pull/722) - 技術的な実装の詳細 + +
diff --git a/VRGDG_Musubi-tuner/docs/wan.md b/VRGDG_Musubi-tuner/docs/wan.md new file mode 100644 index 0000000000000000000000000000000000000000..f93661874386ab440aff37c1650bb1429bf53761 --- /dev/null +++ b/VRGDG_Musubi-tuner/docs/wan.md @@ -0,0 +1,628 @@ +> 📝 Click on the language section to expand / 言語をクリックして展開 + +# Wan 2.1/2.2 + +## Overview / 概要 + +This is an unofficial training and inference script for [Wan2.1](https://github.com/Wan-Video/Wan2.1) and [Wan2.2](https://github.com/Wan-Video/Wan2.2). The features are as follows. + +- fp8 support and memory reduction by block swap: Inference of a 720x1280x81frames videos with 24GB VRAM, training with 720x1280 images with 24GB VRAM +- Inference without installing Flash attention (using PyTorch's scaled dot product attention) +- Supports xformers (training and inference) and Sage attention (inference only) +- Support for Wan2.2 model architecture, only for 14B models + +This feature is experimental. + +
+日本語 + +[Wan2.1](https://github.com/Wan-Video/Wan2.1) および [Wan2.2](https://github.com/Wan-Video/Wan2.2) の非公式の学習および推論スクリプトです。 + +以下の特徴があります。 + +- fp8対応およびblock swapによる省メモリ化:720x1280x81framesの動画を24GB VRAMで推論可能、720x1280の画像での学習が24GB VRAMで可能 +- Flash attentionのインストールなしでの実行(PyTorchのscaled dot product attentionを使用) +- xformers(学習と推論)およびSage attention(推論のみ)対応 +- Wan2.2モデルアーキテクチャのサポート(14Bモデルのみ) + +この機能は実験的なものです。 + +
+ +## Download the model / モデルのダウンロード + +### Wan2.1 + +Download the T5 `models_t5_umt5-xxl-enc-bf16.pth` and CLIP `models_clip_open-clip-xlm-roberta-large-vit-huge-14.pth` from the following page: https://huggingface.co/Wan-AI/Wan2.1-I2V-14B-720P/tree/main + +Download the VAE from the above page `Wan2.1_VAE.pth` or download `split_files/vae/wan_2.1_vae.safetensors` from the following page: https://huggingface.co/Comfy-Org/Wan_2.1_ComfyUI_repackaged/tree/main/split_files/vae + +Download the DiT weights from the following page: https://huggingface.co/Comfy-Org/Wan_2.1_ComfyUI_repackaged/tree/main/split_files/diffusion_models + +Wan2.1 Fun Control model weights can be downloaded from [here](https://huggingface.co/alibaba-pai/Wan2.1-Fun-14B-Control). Navigate to each weight page and download. The Fun Control model seems to support not only T2V but also I2V tasks. + +Please select the appropriate weights according to T2V, I2V, resolution, model size, etc. + +`fp16` and `bf16` models can be used, and `fp8_e4m3fn` models can be used if `--fp8` (or `--fp8_base`) is specified without specifying `--fp8_scaled`. **Please note that `fp8_scaled` models are not supported even with `--fp8_scaled`.** + +(Thanks to Comfy-Org for providing the repackaged weights.) + +### Wan2.2 + +T5 is same as Wan2.1. CLIP is not required for Wan2.2. + +VAE is also same as Wan2.1. Please use `Wan2.1_VAE.pth` from the above page. `Wan2.2_VAE.pth` is for 5B model, not compatible with 14B model. + +Download the DiT weights from the following page: https://huggingface.co/Comfy-Org/Wan_2.2_ComfyUI_Repackaged/tree/main/split_files/diffusion_models + +The Wan2.2 model consists of two DiT models, one for high noise and one for low noise. Please download both. + +`fp16` models can be used. **Please note that `fp8_scaled` models are not supported even with `--fp8_scaled`.** + +### Model support matrix / モデルサポートマトリックス + +* columns: training dtype (行:学習時のデータ型) +* rows: model dtype (列:モデルのデータ型) + +| model \ training |bf16|fp16|--fp8_base|--fp8base & --fp8_scaled| +|---|---|---|---|---| +|bf16|✓|--|✓|✓| +|fp16|--|✓|✓|✓| +|fp8_e4m3fn|--|--|✓|--| +|fp8_scaled|--|--|--|--| + +
+日本語 + +### Wan2.1 + +T5 `models_t5_umt5-xxl-enc-bf16.pth` およびCLIP `models_clip_open-clip-xlm-roberta-large-vit-huge-14.pth` を、次のページからダウンロードしてください:https://huggingface.co/Wan-AI/Wan2.1-I2V-14B-720P/tree/main + +VAEは上のページから `Wan2.1_VAE.pth` をダウンロードするか、次のページから `split_files/vae/wan_2.1_vae.safetensors` をダウンロードしてください:https://huggingface.co/Comfy-Org/Wan_2.1_ComfyUI_repackaged/tree/main/split_files/vae + +DiTの重みを次のページからダウンロードしてください:https://huggingface.co/Comfy-Org/Wan_2.1_ComfyUI_repackaged/tree/main/split_files/diffusion_models + +Wan2.1 Fun Controlモデルの重みは、[こちら](https://huggingface.co/alibaba-pai/Wan2.1-Fun-14B-Control)から、それぞれの重みのページに遷移し、ダウンロードしてください。Fun ControlモデルはT2VだけでなくI2Vタスクにも対応しているようです。 + +T2VやI2V、解像度、モデルサイズなどにより適切な重みを選択してください。 + +`fp16` および `bf16` モデルを使用できます。また、`--fp8` (または`--fp8_base`)を指定し`--fp8_scaled`を指定をしないときには `fp8_e4m3fn` モデルを使用できます。**`fp8_scaled` モデルはいずれの場合もサポートされていませんのでご注意ください。** + +(repackaged版の重みを提供してくださっているComfy-Orgに感謝いたします。) + +### Wan2.2 + +T5はWan2.1と同じです。Wan2.2ではCLIPは不要です。 + +VAEは上のページから `Wan2.1_VAE.pth` をダウンロードしてください。`Wan2.2_VAE.pth` は5Bモデル用で、14Bモデルには対応していません。 + +DiTの重みを次のページからダウンロードしてください:https://huggingface.co/Comfy-Org/Wan_2.2_ComfyUI_Repackaged/tree/main/split_files/diffusion_models + +Wan2.2モデルは高ノイズ用と低ノイズ用の2つのDiTモデルで構成されています。両方をダウンロードしてください。 + +`fp16` モデルを使用できます。**`fp8_scaled` モデルはサポートされませんのでご注意ください。** + +
+ +## Pre-caching / 事前キャッシュ + +Pre-caching is almost the same as in HunyuanVideo, but some options may differ. See [HunyuanVideo documentation](./hunyuan_video.md#pre-caching--事前キャッシング) and `--help` for details. + +### Latent Pre-caching + +Create the cache using the following command: + +```bash +python src/musubi_tuner/wan_cache_latents.py --dataset_config path/to/toml --vae path/to/wan_vae.safetensors +``` + +**If you train I2V models, add `--i2v` option to the above command.** For Wan2.1, add `--clip path/to/models_clip_open-clip-xlm-roberta-large-vit-huge-14.pth` to specify the CLIP model. If not specified, the training will raise an error. For Wan2.2, CLIP model is not required. + +If you're running low on VRAM, specify `--vae_cache_cpu` to use the CPU for the VAE internal cache, which will reduce VRAM usage somewhat. + +The control video settings are required for training the Fun-Control model. Please refer to [Dataset Settings](./dataset_config.md#sample-for-video-dataset-with-control-images) for details. + +
+日本語 + +事前キャッシングはHunyuanVideoとほぼ同じです。オプションが異なる場合がありますので、詳細は[HunyuanVideoのドキュメント](./hunyuan_video.md#pre-caching--事前キャッシング)および`--help`を参照してください。 + +latentの事前キャッシングは上のコマンド例を使用してキャッシュを作成してください。 + +**I2Vモデルを学習する場合は、`--i2v` オプションを上のコマンドに追加してください。**Wan2.1の場合は、`--clip path/to/models_clip_open-clip-xlm-roberta-large-vit-huge-14.pth` を追加してCLIPモデルを指定してください。指定しないと学習時にエラーが発生します。Wan2.2ではCLIPモデルは不要です。 + +VRAMが不足している場合は、`--vae_cache_cpu` を指定するとVAEの内部キャッシュにCPUを使うことで、使用VRAMを多少削減できます。 + +Fun-Controlモデルを学習する場合は、制御用動画の設定が必要です。[データセット設定](./dataset_config.md#sample-for-video-dataset-with-control-images)を参照してください。 + +
+ +### Text Encoder Output Pre-caching + +Text encoder output pre-caching is also almost the same as in HunyuanVideo. Create the cache using the following command: + +```bash +python src/musubi_tuner/wan_cache_text_encoder_outputs.py --dataset_config path/to/toml --t5 path/to/models_t5_umt5-xxl-enc-bf16.pth --batch_size 16 +``` + +Adjust `--batch_size` according to your available VRAM. + +For systems with limited VRAM (less than ~16GB), use `--fp8_t5` to run the T5 in fp8 mode. + +
+日本語 + +テキストエンコーダ出力の事前キャッシングもHunyuanVideoとほぼ同じです。上のコマンド例を使用してキャッシュを作成してください。 + +使用可能なVRAMに合わせて `--batch_size` を調整してください。 + +VRAMが限られているシステム(約16GB未満)の場合は、T5をfp8モードで実行するために `--fp8_t5` を使用してください。 + +
+ +## Training / 学習 + +### Training + +Start training using the following command (input as a single line): + +```bash +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 src/musubi_tuner/wan_train_network.py \ + --task t2v-1.3B \ + --dit path/to/wan2.1_xxx_bf16.safetensors \ + --dataset_config path/to/toml --sdpa --mixed_precision bf16 --fp8_base \ + --optimizer_type adamw8bit --learning_rate 2e-4 --gradient_checkpointing \ + --max_data_loader_n_workers 2 --persistent_data_loader_workers \ + --network_module networks.lora_wan --network_dim 32 \ + --timestep_sampling shift --discrete_flow_shift 3.0 \ + --max_train_epochs 16 --save_every_n_epochs 1 --seed 42 \ + --output_dir path/to/output_dir --output_name name-of-lora +``` +The above is an example. The appropriate values for `timestep_sampling` and `discrete_flow_shift` need to be determined by experimentation. + +For additional options, use `python src/musubi_tuner/wan_train_network.py --help` (note that many options are unverified). + +`--task` is one of `t2v-1.3B`, `t2v-14B`, `i2v-14B`, `t2i-14B` (for Wan2.1 official models), `t2v-1.3B-FC`, `t2v-14B-FC`, and `i2v-14B-FC` (for Wan2.1 Fun Control model), `t2v-A14B`, `i2v-A14B` (for Wan2.2 14B models). Specify the DiT weights for the task with `--dit`. + +You can limit the range of timesteps for training with `--min_timestep` and `--max_timestep`. The values are specified in the range of 0 to 1000 (not 0.0 to 1.0). See [here](./advanced_config.md#specify-time-step-range-for-training--学習時のタイムステップ範囲の指定) for details. + +For Wan2.2 models, if you want to train with either the high-noise model or the low-noise model, specify the model with `--dit` as in Wan2.1. In this case, it is recommended to specify the range of timesteps described in the table below, and `--preserve_distribution_shape` to maintain the distribution shape. + +If you want to train LoRA for both models simultaneously, you need to specify the low-noise model with `--dit` and the high-noise model with `--dit_high_noise`. The two models are switched at the timestep specified by `--timestep_boundary`. The default value is 0.9 for I2V and 0.875 for T2V. `--timestep_boundary` can be specified in the range of 0.0 to 1.0, or in the range of 0 to 1000. + +When training Wan2.2 high and low models, you can use `--offload_inactive_dit` to offload the inactive DiT model to the CPU, which can save VRAM (only works when `--blocks_to_swap` is not specified). Please note that in Windows environment, this offloading uses shared VRAM. Even with fp8/fp8_scaled, about 42GB of shared VRAM is required for the two models combined, which means that about 96GB or more of main RAM is required. If you have less main RAM, using `--blocks_to_swap` will use less main RAM. + +`--gradient_checkpointing` and `--gradient_checkpointing_cpu_offload` are available for memory savings. See [HunyuanVideo documentation](./hunyuan_video.md#memory-optimization) for details. + +For Wan2.2 models, `--discrete_flow_shift` may need to be adjusted based on I2V and T2V. According to the official implementation, the shift values in inference are 12.0 for T2V and 5.0 for I2V. The shift values during training do not necessarily have to match those during inference, but they may serve as a useful reference. + +`--force_v2_1_time_embedding` uses the same shape of time embedding as Wan2.1. This can reduce VRAM usage during inference and training (the larger the resolution and number of frames, the greater the reduction). Although this is different from the official implementation of Wan2.2, it seems that there is no effect on inference or training within the range that has been confirmed. + +Don't forget to specify `--network_module networks.lora_wan`. + +Other options are mostly the same as `hv_train_network.py`. See [HunyuanVideo documentation](./hunyuan_video.md#training--学習) and `--help` for details. + +The trained LoRA weights are seemed to be compatible with ComfyUI (may depend on the nodes used). + +#### Recommended Min/Max Timestep Settings for Wan2.2 + +| Model | Min Timestep | Max Timestep | +|-------|--------------|--------------| +| I2V low noise | 0 | 900 | +| I2V high noise | 900 | 1000 | +| T2V low noise | 0 | 875 | +| T2V high noise | 875 | 1000 | + +
+日本語 + +サンプルは英語版を参照してください。 + +`timestep_sampling`や`discrete_flow_shift`は一例です。どのような値が適切かは実験が必要です。 + +その他のオプションについては `python src/musubi_tuner/wan_train_network.py --help` を使用してください(多くのオプションは未検証です)。 + +`--task` には `t2v-1.3B`, `t2v-14B`, `i2v-14B`, `t2i-14B` (これらはWan2.1公式モデル)、`t2v-1.3B-FC`, `t2v-14B-FC`, `i2v-14B-FC`(Wan2.1-Fun Controlモデル)、`t2v-A14B`, `i2v-A14B`(Wan2.2 14Bモデル)を指定します。`--dit`に、taskに応じたDiTの重みを指定してください。 + +`--min_timestep`と`--max_timestep`で学習するタイムステップの範囲を限定できます。値は0から1000の範囲で指定します。詳細は[こちら](./advanced_config.md#specify-time-step-range-for-training--学習時のタイムステップ範囲の指定)を参照してください。 + +Wan2.2モデルの場合、高ノイズ用モデルまたは低ノイズ用モデルのどちらかで学習する場合は、Wan2.1の場合と同様に、`--dit`にそのモデルを指定してください。またこの場合、英語版サンプル内の表に示すようにタイムステップの範囲を指定し、`--preserve_distribution_shape` を指定して分布形状を維持することをお勧めします。 + +両方のモデルへのLoRAを学習する場合は、`--dit`に低ノイズ用モデルを、`--dit_high_noise`に高ノイズ用モデルを指定します。2つのモデルは`--timestep_boundary`で指定されたタイムステップで切り替わります。デフォルトはI2Vの場合は0.9、T2Vの場合は0.875です。`--timestep_boundary`は0.0から1.0の範囲の値、または0から1000の範囲の値で指定できます。 + +またWan2.2モデルで両方のモデルを学習するとき、`--offload_inactive_dit`を使用すると、使用していないDiTモデルをCPUにオフロードすることができ、VRAMを節約できます(`--blocks_to_swap`未指定時のみ有効)。なお、Windows環境の場合、このオフロードには共有VRAMが使用されます。fp8/fp8_scaledの場合でも2つのモデル合計で約42GBの共有VRAMが必要となり、つまりメインRAMが96GB程度以上必要になりますのでご注意ください。メインRAMが少ない場合、`--blocks_to_swap`を使用する方がメインRAMの使用量は少なくなります。 + +Wan2.2の場合、I2VとT2Vで`--discrete_flow_shift`を調整する必要があるかもしれません。公式実装によると、推論時のシフト値はT2Vで12.0、I2Vで5.0です。学習時のシフト値は推論時度必ずしも合わせる必要はありませんが、参考になるかもしれません。 + +`--force_v2_1_time_embedding` を指定すると、Wan2.1と同じ形状の時間埋め込みを使用します。これにより推論中、学習中のVRAM使用量を削減できます(解像度やフレーム数が大きいほど削減量も大きくなります)。Wan2.2の公式実装とは異なりますが、確認した範囲では推論、学習共に影響はないようです。 + +`--network_module` に `networks.lora_wan` を指定することを忘れないでください。 + +その他のオプションは、ほぼ`hv_train_network.py`と同様です。[HunyuanVideoのドキュメント](./hunyuan_video.md#training--学習)および`--help`を参照してください。 + +学習後のLoRAの重みはそのままComfyUIで使用できるようです(用いるノードにもよります)。 + +
+ +### Command line options for training with sampling / サンプル画像生成に関連する学習時のコマンドラインオプション + +Example of command line options for training with sampling / 記述例: + +```bash +--vae path/to/wan_vae.safetensors \ +--t5 path/to/models_t5_umt5-xxl-enc-bf16.pth \ +--sample_prompts /path/to/prompt_file.txt \ +--sample_every_n_epochs 1 --sample_every_n_steps 1000 --sample_at_first +``` +Each option is the same as when generating images or as HunyuanVideo. Please refer to [here](/docs/sampling_during_training.md) for details. + +If you train I2V models for Wan2.1, add `--clip path/to/models_clip_open-clip-xlm-roberta-large-vit-huge-14.pth` to specify the CLIP model. For Wan2.2, CLIP model is not required. + +You can specify the initial image, the negative prompt and the control video (for Wan2.1-Fun-Control) in the prompt file. Please refer to [here](/docs/sampling_during_training.md#prompt-file--プロンプトファイル). + +
+日本語 + +各オプションは推論時、およびHunyuanVideoの場合と同様です。[こちら](/docs/sampling_during_training.md)を参照してください。 + +Wan2.1のI2Vモデルを学習する場合は、`--clip path/to/models_clip_open-clip-xlm-roberta-large-vit-huge-14.pth` を追加してCLIPモデルを指定してください。Wan2.2ではCLIPモデルは不要です。 + +プロンプトファイルで、初期画像やネガティブプロンプト、制御動画(Wan2.1-Fun-Control用)等を指定できます。[こちら](/docs/sampling_during_training.md#prompt-file--プロンプトファイル)を参照してください。 + +
+ + +## Inference / 推論 + +### Inference Options Comparison / 推論オプション比較 + +#### Speed Comparison (Faster → Slower) / 速度比較(速い→遅い) +*Note: Results may vary depending on GPU type* + +fp8_fast > bf16/fp16 (no block swap) > fp8 > fp8_scaled > bf16/fp16 (block swap) + +#### Quality Comparison (Higher → Lower) / 品質比較(高→低) + +bf16/fp16 > fp8_scaled > fp8 >> fp8_fast + +### T2V Inference / T2V推論 + +The following is an example of T2V inference (input as a single line): + +```bash +python src/musubi_tuner/wan_generate_video.py --fp8 --task t2v-1.3B --video_size 832 480 --video_length 81 --infer_steps 20 \ +--prompt "prompt for the video" --save_path path/to/save.mp4 --output_type both \ +--dit path/to/wan2.1_t2v_1.3B_bf16_etc.safetensors --vae path/to/wan_2.1_vae.safetensors \ +--t5 path/to/models_t5_umt5-xxl-enc-bf16.pth \ +--attn_mode torch +``` + +`--task` is one of `t2v-1.3B`, `t2v-14B`, `i2v-14B`, `t2i-14B` (these are Wan2.1 official models), `t2v-1.3B-FC`, `t2v-14B-FC` and `i2v-14B-FC` (for Wan2.1-Fun Control model), `t2v-A14B`, `i2v-A14B` (for Wan2.2 14B models). + +For Wan2.2 models, you can specify the low-noise model with `--dit` and the high-noise model with `--dit_high_noise`. The two models are switched at the timestep specified by `--timestep_boundary`. The default is described above. If you omit the high-noise model, the low-noise model will be used for all timesteps. + +When inferring Wan2 .2 high and low models, you can use `--offload_inactive_dit` to offload the inactive DiT model to the CPU, or `--lazy_loading` to enable lazy loading for DiT models, which can save VRAM. `--offload_inactive_dit` only works when `--blocks_to_swap` is not specified, so use `--lazy_loading` instead. Without these options, both models will remain on the GPU, which may use more VRAM. + +`--attn_mode` is `torch`, `sdpa` (same as `torch`), `xformers`, `sageattn`,`flash2`, `flash` (same as `flash2`) or `flash3`. `torch` is the default. Other options require the corresponding library to be installed. `flash3` (Flash attention 3) is not tested. + +Specifying `--fp8` runs DiT in fp8 mode. fp8 can significantly reduce memory consumption but may impact output quality. + +`--fp8_scaled` can be specified in addition to `--fp8` to run the model in fp8 weights optimization. This increases memory consumption and speed slightly but improves output quality. See [here](advanced_config.md#fp8-weight-optimization-for-models--モデルの重みのfp8への最適化) for details. + +`--fp8_fast` option is also available for faster inference on RTX 40x0 GPUs. This option requires `--fp8_scaled` option. **This option seems to degrade the output quality.** + +`--fp8_t5` can be used to specify the T5 model in fp8 format. This option reduces memory usage for the T5 model. + +`--negative_prompt` can be used to specify a negative prompt. If omitted, the default negative prompt is used. + +`--flow_shift` can be used to specify the flow shift (default 3.0 for I2V with 480p, 5.0 for others). + +`--guidance_scale` can be used to specify the guidance scale for classifier free guidance (default 5.0). For Wan2.2, `--guidance_scale_high_noise` also can be specified to set a different scale for the high-noise model. + +`--blocks_to_swap` is the number of blocks to swap during inference. The default value is None (no block swap). The maximum value is 39 for 14B model and 29 for 1.3B model. + +`--force_v2_1_time_embedding` uses the same shape of time embedding as Wan2.1 for Wan2.2. See the training section for details. + +`--vae_cache_cpu` enables VAE cache in main memory. This reduces VRAM usage slightly but processing is slower. + +`--compile` enables torch.compile. See [here](/README.md#inference) for details. + +`--trim_tail_frames` can be used to trim the tail frames when saving. The default is 0. + +`--cfg_skip_mode` specifies the mode for skipping CFG in different steps. The default is `none` (all steps).`--cfg_apply_ratio` specifies the ratio of steps where CFG is applied. See below for details. + +`--include_patterns` and `--exclude_patterns` can be used to specify which LoRA modules to apply or exclude during training. If not specified, all modules are applied by default. These options accept regular expressions. + +`--include_patterns` specifies the modules to be applied, and `--exclude_patterns` specifies the modules to be excluded. The regular expression is matched against the LoRA key name, and include takes precedence. + +The key name to be searched is in sd-scripts format (`lora_unet_`). For example, `lora_unet_blocks_9_cross_attn_k`. + +For example, if you specify `--exclude_patterns "blocks_[23]\d_"` , it will exclude modules containing `blocks_20` to `blocks_39`. If you specify `--include_patterns "cross_attn" --exclude_patterns "blocks_(0|1|2|3|4)_"`, it will apply LoRA to modules containing `cross_attn` and not containing `blocks_0` to `blocks_4`. + +If you specify multiple LoRA weights, please specify them with multiple arguments. For example: `--include_patterns "cross_attn" ".*" --exclude_patterns "dummy_do_not_exclude" "blocks_(0|1|2|3|4)"`. `".*"` is a regex that matches everything. `dummy_do_not_exclude` is a dummy regex that does not match anything. + +`--cpu_noise` generates initial noise on the CPU. This may result in the same results as ComfyUI with the same seed (depending on other settings). + +If you are using the Fun Control model, specify the control video with `--control_path`. You can specify a video file or a folder containing multiple image files. The number of frames in the video file (or the number of images) should be at least the number specified in `--video_length` (plus 1 frame if you specify `--end_image_path`). + +Please try to match the aspect ratio of the control video with the aspect ratio specified in `--video_size` (there may be some deviation from the initial image of I2V due to the use of bucketing processing). + +Other options are same as `hv_generate_video.py` (some options are not supported, please check the help). + +
+日本語 + +`--task` には `t2v-1.3B`, `t2v-14B`, `i2v-14B`, `t2i-14B` (これらはWan2.1公式モデル)、`t2v-1.3B-FC`, `t2v-14B-FC`, `i2v-14B-FC`(Wan2.1-Fun Controlモデル)、`t2v-A14B`, `i2v-A14B`(Wan2.2 14Bモデル)を指定します。 + +Wan2.2モデルの場合、`--dit`に低ノイズ用モデルを、`--dit_high_noise`に高ノイズ用モデルを指定します。2つのモデルは`--timestep_boundary`で指定されたタイムステップで切り替わります。高ノイズ用モデルを省略した場合は、低ノイズ用モデルが全てのタイムステップで使用されます。 + +またWan2.2モデルで両方のモデルを用いて推論するとき、`--offload_inactive_dit`を使用すると、使用していないDiTモデルをCPUにオフロードすることができます。また`--lazy_loading`を使用すると、DiTモデルの遅延読み込みを有効します。これらのオプションによりVRAMを節約できます。`--offload_inactive_dit`は`--blocks_to_swap`が指定されていない場合にのみ利用できます。`--block_to_swap`を使うときには`--lazy_loading`を使用してください。これらのオプションを指定しないと両方のモデルがGPUに置かれますので、VRAMを多く使用します。 + +`--attn_mode` には `torch`, `sdpa`(`torch`と同じ)、`xformers`, `sageattn`, `flash2`, `flash`(`flash2`と同じ), `flash3` のいずれかを指定します。デフォルトは `torch` です。その他のオプションを使用する場合は、対応するライブラリをインストールする必要があります。`flash3`(Flash attention 3)は未テストです。 + +`--fp8` を指定するとDiTモデルをfp8形式で実行します。fp8はメモリ消費を大幅に削減できますが、出力品質に影響を与える可能性があります。 + +`--fp8_scaled` を `--fp8` と併用すると、fp8への重み量子化を行います。メモリ消費と速度はわずかに悪化しますが、出力品質が向上します。詳しくは[こちら](advanced_config.md#fp8-weight-optimization-for-models--モデルの重みのfp8への最適化)を参照してください。 + +`--fp8_fast` オプションはRTX 40x0 GPUでの高速推論に使用されるオプションです。このオプションは `--fp8_scaled` オプションが必要です。**出力品質が劣化するようです。** + +`--fp8_t5` を指定するとT5モデルをfp8形式で実行します。T5モデル呼び出し時のメモリ使用量を削減します。 + +`--negative_prompt` でネガティブプロンプトを指定できます。省略した場合はデフォルトのネガティブプロンプトが使用されます。 + +`--flow_shift` でflow shiftを指定できます(480pのI2Vの場合はデフォルト3.0、それ以外は5.0)。 + +`--guidance_scale` でclassifier free guianceのガイダンススケールを指定できます(デフォルト5.0)。Wan2.2の場合は、`--guidance_scale_high_noise` で高ノイズ用モデルのガイダンススケールを別に指定できます。 + +`--blocks_to_swap` は推論時のblock swapの数です。デフォルト値はNone(block swapなし)です。最大値は14Bモデルの場合39、1.3Bモデルの場合29です。 + +`--force_v2_1_time_embedding` はWan2.2の場合に有効で、Wan2.1と同じ形状の時間埋め込みを使用します。詳細は学習セクションを参照してください。 + +`--vae_cache_cpu` を有効にすると、VAEのキャッシュをメインメモリに保持します。VRAM使用量が多少減りますが、処理は遅くなります。 + +`--compile`でtorch.compileを有効にします。詳細については[こちら](/README.md#inference)を参照してください。 + +`--trim_tail_frames` で保存時に末尾のフレームをトリミングできます。デフォルトは0です。 + +`--cfg_skip_mode` は異なるステップでCFGをスキップするモードを指定します。デフォルトは `none`(全ステップ)。`--cfg_apply_ratio` はCFGが適用されるステップの割合を指定します。詳細は後述します。 + +LoRAのどのモジュールを適用するかを、`--include_patterns`と`--exclude_patterns`で指定できます(未指定時・デフォルトは全モジュール適用されます +)。これらのオプションには、正規表現を指定します。`--include_patterns`は適用するモジュール、`--exclude_patterns`は適用しないモジュールを指定します。正規表現がLoRAのキー名に含まれるかどうかで判断され、includeが優先されます。 + +検索対象となるキー名は sd-scripts 形式(`lora_unet_<モジュール名のドットを_に置換したもの>`)です。例:`lora_unet_blocks_9_cross_attn_k` + +たとえば `--exclude_patterns "blocks_[23]\d_"`のみを指定すると、`blocks_20`から`blocks_39`を含むモジュールが除外されます。`--include_patterns "cross_attn" --exclude_patterns "blocks_(0|1|2|3|4)_"`のようにincludeとexcludeを指定すると、`cross_attn`を含むモジュールで、かつ`blocks_0`から`blocks_4`を含まないモジュールにLoRAが適用されます。 + +複数のLoRAの重みを指定する場合は、複数個の引数で指定してください。例:`--include_patterns "cross_attn" ".*" --exclude_patterns "dummy_do_not_exclude" "blocks_(0|1|2|3|4)"` `".*"`は全てにマッチする正規表現です。`dummy_do_not_exclude`は何にもマッチしないダミーの正規表現です。 + +`--cpu_noise`を指定すると初期ノイズをCPUで生成します。これにより同一seed時の結果がComfyUIと同じになる可能性があります(他の設定にもよります)。 + +Fun Controlモデルを使用する場合は、`--control_path`で制御用の映像を指定します。動画ファイル、または複数枚の画像ファイルを含んだフォルダを指定できます。動画ファイルのフレーム数(または画像の枚数)は、`--video_length`で指定したフレーム数以上にしてください(後述の`--end_image_path`を指定した場合は、さらに+1フレーム)。 + +制御用の映像のアスペクト比は、`--video_size`で指定したアスペクト比とできるかぎり合わせてください(bucketingの処理を流用しているためI2Vの初期画像とズレる場合があります)。 + +その他のオプションは `hv_generate_video.py` と同じです(一部のオプションはサポートされていないため、ヘルプを確認してください)。 + +
+ +#### CFG Skip Mode / CFGスキップモード + + These options allow you to balance generation speed against prompt accuracy. More skipped steps results in faster generation with potential quality degradation. + +Setting `--cfg_apply_ratio` to 0.5 speeds up the denoising loop by up to 25%. + +`--cfg_skip_mode` specified one of the following modes: + +- `early`: Skips CFG in early steps for faster generation, applying guidance mainly in later refinement steps +- `late`: Skips CFG in later steps, applying guidance during initial structure formation +- `middle`: Skips CFG in middle steps, applying guidance in both early and later steps +- `early_late`: Skips CFG in both early and late steps, applying only in middle steps +- `alternate`: Applies CFG in alternate steps based on the specified ratio +- `none`: Applies CFG at all steps (default) + +`--cfg_apply_ratio` specifies a value from 0.0 to 1.0 controlling the proportion of steps where CFG is applied. For example, setting 0.5 means CFG will be applied in only 50% of the steps. + +If num_steps is 10, the following table shows the steps where CFG is applied based on the `--cfg_skip_mode` option (A means CFG is applied, S means it is skipped, `--cfg_apply_ratio` is 0.6): + +| skip mode | CFG apply pattern | +|---|---| +| early | SSSSAAAAAA | +| late | AAAAAASSSS | +| middle | AAASSSSAAA | +| early_late | SSAAAAAASS | +| alternate | SASASAASAS | + +The appropriate settings are unknown, but you may want to try `late` or `early_late` mode with a ratio of around 0.3 to 0.5. +
+日本語 +これらのオプションは、生成速度とプロンプトの精度のバランスを取ることができます。スキップされるステップが多いほど、生成速度が速くなりますが、品質が低下する可能性があります。 + +ratioに0.5を指定することで、デノイジングのループが最大25%程度、高速化されます。 + +`--cfg_skip_mode` は次のモードのいずれかを指定します: + +- `early`:初期のステップでCFGをスキップして、主に終盤の精細化のステップで適用します +- `late`:終盤のステップでCFGをスキップし、初期の構造が決まる段階で適用します +- `middle`:中間のステップでCFGをスキップし、初期と終盤のステップの両方で適用します +- `early_late`:初期と終盤のステップの両方でCFGをスキップし、中間のステップのみ適用します +- `alternate`:指定された割合に基づいてCFGを適用します + +`--cfg_apply_ratio` は、CFGが適用されるステップの割合を0.0から1.0の値で指定します。たとえば、0.5に設定すると、CFGはステップの50%のみで適用されます。 + +具体的なパターンは上のテーブルを参照してください。 + +適切な設定は不明ですが、モードは`late`または`early_late`、ratioは0.3~0.5程度から試してみると良いかもしれません。 +
+ +#### Skip Layer Guidance + +Skip Layer Guidance is a feature that uses the output of a model with some blocks skipped as the unconditional output of classifier free guidance. It was originally proposed in [SD 3.5](https://github.com/comfyanonymous/ComfyUI/pull/5404) and first applied in Wan2GP in [this PR](https://github.com/deepbeepmeep/Wan2GP/pull/61). It may improve the quality of generated videos. + +The implementation of SD 3.5 is [here](https://github.com/Stability-AI/sd3.5/blob/main/sd3_impls.py), and the implementation of Wan2GP (the PR mentioned above) has some different specifications. This inference script allows you to choose between the two methods. + +*The SD3.5 method applies slg output in addition to cond and uncond (slows down the speed). The Wan2GP method uses only cond and slg output.* + +The following arguments are available: + +- `--slg_mode`: Specifies the SLG mode. `original` for SD 3.5 method, `uncond` for Wan2GP method. Default is None (no SLG). +- `--slg_layers`: Specifies the indices of the blocks (layers) to skip in SLG, separated by commas. Example: `--slg_layers 4,5,6`. Default is empty (no skip). If this option is not specified, `--slg_mode` is ignored. +- `--slg_scale`: Specifies the scale of SLG when `original`. Default is 3.0. +- `--slg_start`: Specifies the start step of SLG application in inference steps from 0.0 to 1.0. Default is 0.0 (applied from the beginning). +- `--slg_end`: Specifies the end step of SLG application in inference steps from 0.0 to 1.0. Default is 0.3 (applied up to 30% from the beginning). + +Appropriate settings are unknown, but you may want to try `original` mode with a scale of around 3.0 and a start ratio of 0.0 and an end ratio of 0.5, with layers 4, 5, and 6 skipped. + +
+日本語 +Skip Layer Guidanceは、一部のblockをスキップしたモデル出力をclassifier free guidanceのunconditional出力に使用する機能です。元々は[SD 3.5](https://github.com/comfyanonymous/ComfyUI/pull/5404)で提案されたもので、Wan2.1には[Wan2GPのこちらのPR](https://github.com/deepbeepmeep/Wan2GP/pull/61)で初めて適用されました。生成動画の品質が向上する可能性があります。 + +SD 3.5の実装は[こちら](https://github.com/Stability-AI/sd3.5/blob/main/sd3_impls.py)で、Wan2GPの実装(前述のPR)は一部仕様が異なります。この推論スクリプトでは両者の方式を選択できるようになっています。 + +※SD3.5方式はcondとuncondに加えてslg outputを適用します(速度が低下します)。Wan2GP方式はcondとslg outputのみを使用します。 + +以下の引数があります。 + +- `--slg_mode`:SLGのモードを指定します。`original`でSD 3.5の方式、`uncond`でWan2GPの方式です。デフォルトはNoneで、SLGを使用しません。 +- `--slg_layers`:SLGでスキップするblock (layer)のインデクスをカンマ区切りで指定します。例:`--slg_layers 4,5,6`。デフォルトは空(スキップしない)です。このオプションを指定しないと`--slg_mode`は無視されます。 +- `--slg_scale`:`original`のときのSLGのスケールを指定します。デフォルトは3.0です。 +- `--slg_start`:推論ステップのSLG適用開始ステップを0.0から1.0の割合で指定します。デフォルトは0.0です(最初から適用)。 +- `--slg_end`:推論ステップのSLG適用終了ステップを0.0から1.0の割合で指定します。デフォルトは0.3です(最初から30%まで適用)。 + +適切な設定は不明ですが、`original`モードでスケールを3.0程度、開始割合を0.0、終了割合を0.5程度に設定し、4, 5, 6のlayerをスキップする設定から始めると良いかもしれません。 +
+ +### I2V Inference / I2V推論 + +The following is an example of I2V inference (input as a single line): + +```bash +python src/musubi_tuner/wan_generate_video.py --fp8 --task i2v-14B --video_size 832 480 --video_length 81 --infer_steps 20 \ +--prompt "prompt for the video" --save_path path/to/save.mp4 --output_type both \ +--dit path/to/wan2.1_i2v_480p_14B_bf16_etc.safetensors --vae path/to/wan_2.1_vae.safetensors \ +--t5 path/to/models_t5_umt5-xxl-enc-bf16.pth --clip path/to/models_clip_open-clip-xlm-roberta-large-vit-huge-14.pth \ +--attn_mode torch --image_path path/to/image.jpg +``` + +For Wan2.1, add `--clip` to specify the CLIP model. For Wan2.2, CLIP model is not required. `--image_path` is the path to the image to be used as the initial frame. + +`--end_image_path` can be used to specify the end image. This option is experimental. When this option is specified, the saved video will be slightly longer than the specified number of frames and will have noise, so it is recommended to specify `--trim_tail_frames 3` to trim the tail frames. + +You can also use the Fun Control model for I2V inference. Specify the control video with `--control_path`. + +Other options are same as T2V inference. + +
+日本語 +Wan2.1の場合は`--clip` を追加してCLIPモデルを指定します。Wan2.2ではCLIPモデルは不要です。`--image_path` は初期フレームとして使用する画像のパスです。 + +`--end_image_path` で終了画像を指定できます。このオプションは実験的なものです。このオプションを指定すると、保存される動画が指定フレーム数よりもやや多くなり、かつノイズが乗るため、`--trim_tail_frames 3` などを指定して末尾のフレームをトリミングすることをお勧めします。 + +I2V推論でもFun Controlモデルが使用できます。`--control_path` で制御用の映像を指定します。 + +その他のオプションはT2V推論と同じです。 +
+ +### New Batch and Interactive Modes / 新しいバッチモードとインタラクティブモード + +In addition to single video generation, Wan 2.1/2.2 now supports batch generation from file and interactive prompt input: + +#### Batch Mode from File / ファイルからのバッチモード + +Generate multiple videos from prompts stored in a text file: + +```bash +python src/musubi_tuner/wan_generate_video.py --from_file prompts.txt --task t2v-14B \ +--dit path/to/model.safetensors --vae path/to/vae.safetensors \ +--t5 path/to/t5_model.pth --save_path output_directory +``` + +The prompts file format: +- One prompt per line +- Empty lines and lines starting with # are ignored (comments) +- Each line can include prompt-specific parameters using command-line style format: + +``` +A beautiful sunset over mountains --w 832 --h 480 --f 81 --d 42 --s 20 +A busy city street at night --w 480 --h 832 --g 7.5 --n low quality, blurry +``` + +Supported inline parameters (if ommitted, default values from the command line are used): +- `--w`: Width +- `--h`: Height +- `--f`: Frame count +- `--d`: Seed +- `--s`: Inference steps +- `--g` or `--l`: Guidance scale +- `--fs`: Flow shift +- `--i`: Image path (for I2V) +- `--cn`: Control path (for Fun Control) +- `--n`: Negative prompt + +In batch mode, models are loaded once and reused for all prompts, significantly improving overall generation time compared to multiple single runs. + +#### Interactive Mode / インタラクティブモード + +Interactive command-line interface for entering prompts: + +```bash +python src/musubi_tuner/wan_generate_video.py --interactive --task t2v-14B \ +--dit path/to/model.safetensors --vae path/to/vae.safetensors \ +--t5 path/to/t5_model.pth --save_path output_directory +``` + +In interactive mode: +- Enter prompts directly at the command line +- Use the same inline parameter format as batch mode +- Use Ctrl+D (or Ctrl+Z on Windows) to exit +- Models remain loaded between generations for efficiency + +
+日本語 +単一動画の生成に加えて、Wan 2.1/2.2は現在、ファイルからのバッチ生成とインタラクティブなプロンプト入力をサポートしています。 + +#### ファイルからのバッチモード + +テキストファイルに保存されたプロンプトから複数の動画を生成します: + +```bash +python src/musubi_tuner/wan_generate_video.py --from_file prompts.txt --task t2v-14B \ +--dit path/to/model.safetensors --vae path/to/vae.safetensors \ +--t5 path/to/t5_model.pth --save_path output_directory +``` + +プロンプトファイルの形式: +- 1行に1つのプロンプト +- 空行や#で始まる行は無視されます(コメント) +- 各行にはコマンドライン形式でプロンプト固有のパラメータを含めることができます: + +サポートされているインラインパラメータ(省略した場合、コマンドラインのデフォルト値が使用されます) +- `--w`: 幅 +- `--h`: 高さ +- `--f`: フレーム数 +- `--d`: シード +- `--s`: 推論ステップ +- `--g` または `--l`: ガイダンススケール +- `--fs`: フローシフト +- `--i`: 画像パス(I2V用) +- `--cn`: コントロールパス(Fun Control用) +- `--n`: ネガティブプロンプト + +バッチモードでは、モデルは一度だけロードされ、すべてのプロンプトで再利用されるため、複数回の単一実行と比較して全体的な生成時間が大幅に改善されます。 + +#### インタラクティブモード + +プロンプトを入力するためのインタラクティブなコマンドラインインターフェース: + +```bash +python src/musubi_tuner/wan_generate_video.py --interactive --task t2v-14B \ +--dit path/to/model.safetensors --vae path/to/vae.safetensors \ +--t5 path/to/t5_model.pth --save_path output_directory +``` + +インタラクティブモードでは: +- コマンドラインで直接プロンプトを入力 +- バッチモードと同じインラインパラメータ形式を使用 +- 終了するには Ctrl+D (Windowsでは Ctrl+Z) を使用 +- 効率のため、モデルは生成間で読み込まれたままになります + +
diff --git a/VRGDG_Musubi-tuner/docs/wan_1f.md b/VRGDG_Musubi-tuner/docs/wan_1f.md new file mode 100644 index 0000000000000000000000000000000000000000..0be1b186e94152bf5499fd98ce205aa4ce260b82 --- /dev/null +++ b/VRGDG_Musubi-tuner/docs/wan_1f.md @@ -0,0 +1,175 @@ +# Wan2.1 One Frame (Single Frame) Inference and Training / Wan2.1 1フレーム推論と学習 + +## Overview / 概要 + +This document describes the application of "One Frame Inference" found in the FramePack model to Wan2.1. + +1. **Basic One Frame Inference**: + * Input the starting image and prompt, limiting the number of frames to generate to 1 frame. Use the Wan2.1 I2V model. + * Intentionally set a large value for the RoPE timestamp assigned to the generated single frame. This aims to obtain a single static image that has changed temporally and semantically according to the prompt from the starting image. + * However, unlike FramePack, using Wan2.1's model as is for inference results in images that are almost identical to the starting image, with noise mixed in. This seems to be due to the characteristics of Wan2.1. + * By additionally training a LoRA, it is possible to reflect changes according to the prompt in the generated image while also reducing noise. + +2. **Intermediate Frame One Frame Inference**: + * Similar to the kisekaeichi method, use the FLF2V (First and Last Frame to Video) method to generate intermediate frames. Use the FLF2V model. + * Set the RoPE timestamp of the generated image to an intermediate value between the timestamps of the starting image and the ending image. + * (This is a theoretical proposal, implemented but not yet tested.) + +
+日本語 + +このドキュメントでは、FramePackモデルで見いだされた「1フレーム推論」の、Wan2.1への適用について説明します。 + +1. **基本的な1フレーム推論**: + * 開始画像とプロンプトを入力とし、生成するフレーム数を1フレームに限定します。Wan2.1の I2V モデルを使用します。 + * この際、生成する1フレームに割り当てるRoPEのタイムスタンプを意図的に大きな値に設定します。これは開始画像からプロンプトに従って時間的・意味的に変化した単一の静止画を得ることを目的としています。 + * しかしながらFramePackと異なり、Wan2.1のモデルをそのまま利用した推論では、このように設定しても生成される画像は開始画像とほぼ同じものになり、またノイズも混ざります。これはWan2.1の特性によるもの思われます。 + * 追加でLoRAを学習することで、プロンプトに従った変化を生成画像に反映させることが可能で、かつノイズも抑えられることがわかりました。 + +2. **中間フレームの1フレーム推論**: + * kisekaeichi方式と似た、FLF2V (First and Last Frame to Video) 方式を利用し、中間のフレームを生成します。FLF2Vモデルを使用します。 + * 生成する画像のRoPEタイムスタンプを、開始画像のタイムスタンプと終端画像のタイムスタンプの中間的な値に設定します。 + +
+ +## One (single) Frame Inference / 1フレーム推論 + +**This feature is highly experimental** and is not officially supported. It is an independent implementation, not an official feature of Wan2.1. + +To perform one-frame inference, specify the `--one_frame_inference` option with `target_index` and `control_index`. In Wan2.1, it is necessary to combine this with LoRA, so please set it up similarly to LoRA training settings. The model used should also be the same. + +An example description is as follows: + +```bash +--output_type latent_images --image_path start_image.png --control_image_path start_image.png \ +--one_frame_inference control_index=0,target_index=1 +``` + +To perform one-frame inference for intermediate frames, specify multiple indices for `control_index` separated by semicolons. The description is as follows: + +```bash +--output_type latent_images --image_path start_image.png --control_image_path start_image.png end_image.png \ +--one_frame_inference control_index=0;2,target_index=1 +``` + +When specifying `--output_type` as `latent_images`, both latent and image will be saved. + +The `--image_path` is used to obtain CLIP features for one-frame inference. Usually, the starting image should be specified. The `--end_image_path` is used to obtain CLIP features for the ending image. Usually, the ending image should be specified. + +The `--control_image_path` is a newly added argument to specify the control image. Usually, the starting image (and both starting and ending images for intermediate frame inference) should be specified. + +The options for `--one_frame_inference` are specified as comma-separated values. Here, the index represents the RoPE timestamp. + +- `target_index=`: Specifies the index of the generated image. +- `control_index=`: Specifies the index of the control image. Please specify the same number of indices as the number of control images specified in `--control_image_path`. + +The optimal values for `target_index` and `control_index` are unknown. Please specify `target_index` as 1 or greater. For one-frame inference, specify `control_index=0`. For intermediate frame one-frame inference, specify `control_index=0;2`, where 0 and a value greater than `target_index` are specified. + +
+日本語 + +**この機能は非常に実験的であり**、公式にはサポートされていません。Wan2.1公式の機能ではなく、独自の実装です。 + +1フレーム推論を行うには`--one_frame_inference`オプションに `target_index` と `control_index` を指定してください。Wan2.1ではLoRAとの組み合わせが必要になりますので、LoRAの学習設定と同様の設定を行ってください。使用するモデルについても同様です。 + +記述例は以下の通りです。 + +```bash +--output_type latent_images --image_path start_image.png --control_image_path start_image.png \ +--one_frame_inference control_index=0,target_index=1 +``` + +中間フレームの1フレーム推論を行うには、`control_index`にセミコロン区切りで複数のインデックスを指定します。以下のように記述します。 + +```bash +--output_type latent_images --image_path start_image.png --end_image_path end_image.png \ +--control_image_path start_image.png end_image.png --one_frame_inference control_index=0;2,target_index=1 +``` + +`--output_type`に`latent_images`を指定するとlatentと画像の両方が保存されます。 + +`--image_path`は、1フレーム推論ではCLIPの特徴量を取得するために用いられます。通常は開始画像を指定してください。`--end_image_path`は、終了画像のCLIP特徴量を取得するために用いられます。通常は終了画像を指定してください。 + +`--control_image_path`は新しく追加された引数で、制御用画像を指定するために用いられます。通常は開始画像(中間フレーム推論の場合は開始画像と終了画像の両方)を指定してください。 + +`--one_frame_inference`のオプションには、カンマ区切りで以下のオプションを指定します。ここでindexはRoPEのタイムスタンプを表します。 + +- `target_index=<整数>`: 生成する画像のindexを指定します。 +- `control_index=<整数またはセミコロン区切りの整数>`: 制御用画像のindexを指定します。`--control_image_path`で指定した制御用画像の数と同じ数のインデックスを指定してください。 + +`target_index`、`control_index`の最適値は不明です。`target_index`は1以上を指定してください。`control_index`は、1フレーム推論では`control_index=0`を指定します。中間フレームの1フレーム推論では、`control_index=0;2`のように、0と`target_index`より大きい値を指定します。 + +
+ +## One Frame (Single Frame) Training / 1フレーム学習 + +**This feature is experimental.** It performs training in a manner similar to one-frame inference. + +This currently reuses the dataset settings of the FramePack model. Please refer to the [FramePack documentation](./framepack_1f.md#one-frame-single-frame-training--1フレーム学習) and the [FramePack dataset settings](./dataset_config.md#framepack-one-frame-training). + +`fp_1f_clean_indices` corresponds to the `control_index` described below. + +However, `fp_1f_no_post` is ignored in Wan2.1, and alpha masks are not yet supported. + +When performing one-frame training, please create the cache by specifying `--one_frame` in `wan_cache_latents.py`. Also, specify `--one_frame` in `wan_train_network.py` to change the inference method for sample image generation. + +In one-frame training, the I2V 14B model is used. Specify `--task i2v-14B` and the corresponding weights. For intermediate frame one-frame training, the FLF2V model is used. Specify `--task flf2v-14B` and the corresponding weights. + +In simple experiments for intermediate frame one-frame training, using `control_index=0;2`, `target_index=1` (in dataset settings, `fp_1f_clean_indices = [0, 2]`, `fp_1f_target_index = 1`), yielded better results than `0;10` and `5`. + +The optimal training settings are currently unknown. Feedback is welcome. + +### Example of prompt file description for sample generation + +The description is almost the same as for FramePack. The command line option `--one_frame_inference` corresponds to `--of`, and `--control_image_path` corresponds to `--ci`. `--ei` is used to specify the ending image. + +Note that while `--ci` can be specified multiple times, it should be specified as `--ci img1.png --ci img2.png`, unlike `--control_image_path` which is specified as `--control_image_path img1.png img2.png`. + +For normal one-frame training: +``` +The girl wears a school uniform. --i path/to/start.png --ci path/to/start.png --of target_index=1,control_index=0 --d 1111 --f 1 --s 10 --fs 7 --d 1234 --w 384 --h 576 +``` + +For intermediate frame one-frame training +``` +The girl wears a school uniform. --i path/to/start.png --ei path/to/end.png --ci path/to/start.png --ci path/to/end.png --of target_index=1,control_index=0;2 --d 1111 --f 1 --s 10 --fs 7 --d 1234 --w 384 --h 576 +``` + +
+日本語 + +**この機能は実験的なものです。** 1フレーム推論と同様の方法で学習を行います。 + +現在は、FramePackモデルのデータセット設定を流用しています。[FramePackのドキュメント](./framepack_1f.md#one-frame-single-frame-training--1フレーム学習)および +[FramePackのデータセット設定](./dataset_config.md#framepack-one-frame-training)を参照してください。 + +`fp_1f_clean_indices` が後述の `control_index` に相当します。 + +ただし、`fp_1f_no_post`はWan2.1では無視されます。またアルファ値によるマスクも未対応です。 + +1フレーム学習時は、`wan_cache_latents.py`に`--one_frame`を指定してキャッシュを作成してください。また、`wan_train_network.py`に`--one_frame`を指定してサンプル画像生成時の推論方法を変更してください。 + +1フレーム学習ではI2Vの14Bモデルを使用します。`--task i2v-14B`を指定し、該当する重みを指定してください。中間フレームの1フレーム学習では、FLF2Vモデルを使用します。`--task flf2v-14B`を指定し、該当する重みを指定してください。 + +中間フレーム学習の簡単な実験では、`control_index=0;2`、`target_index=1`が(データセット設定では `fp_1f_clean_indices = [0, 2]`、`fp_1f_target_index = 1`)、`0;10`および`5`よりも良い結果を得られました。 + +最適な学習設定は今のところ不明です。フィードバックを歓迎します。 + +**サンプル生成のプロンプトファイル記述例** + +FramePackとほぼ同様です。コマンドラインオプション`--one_frame_inference`に相当する `--of`と、`--control_image_path`に相当する`--ci`が用意されています。`--ei`は終端画像を指定します。 + +※ `--control_image_path`は`--control_image_path img1.png img2.png`のようにスペースで区切るのに対して、`--ci`は`--ci img1.png --ci img2.png`のように指定するので注意してください。 + +通常の1フレーム学習: +``` +The girl wears a school uniform. --i path/to/start.png --ci path/to/start.png --of target_index=1,control_index=0 --d 1111 --f 1 --s 10 --fs 7 --d 1234 --w 384 --h 576 +``` + +中間フレームの1フレーム学習(開始画像と終端画像の両方を指定): +``` +The girl wears a school uniform. --i path/to/start.png --ei path/to/end.png --ci path/to/start.png --ci path/to/end.png --of target_index=1,control_index=0;2 --d 1111 --f 1 --s 10 --fs 7 --d 1234 --w 384 --h 576 +``` + +
+ diff --git a/VRGDG_Musubi-tuner/docs/zimage.md b/VRGDG_Musubi-tuner/docs/zimage.md new file mode 100644 index 0000000000000000000000000000000000000000..87c585528283fda1f28cb90aaa3f543654f9fa68 --- /dev/null +++ b/VRGDG_Musubi-tuner/docs/zimage.md @@ -0,0 +1,404 @@ +# Z-Image + +## Overview / 概要 + +This document describes the usage of Z-Image architecture within the Musubi Tuner framework. Z-Image is a model architecture that supports text-to-image generation. + +Pre-caching, training, and inference options can be found via `--help`. Many options are shared with HunyuanVideo, so refer to the [HunyuanVideo documentation](./hunyuan_video.md) as needed. + +This feature is experimental. + +
+日本語 + +このドキュメントは、Musubi Tunerフレームワーク内でのZ-Imageアーキテクチャの使用法について説明しています。Z-Imageはテキストから画像を生成することができるモデルアーキテクチャです。Z-Imageは現在蒸留モデルであるTurbo版しかリリースされていないため、学習は不安定です。モデルのダウンロードの項も参照してください。 + +事前キャッシング、学習、推論のオプションは`--help`で確認してください。HunyuanVideoと共通のオプションが多くありますので、必要に応じて[HunyuanVideoのドキュメント](./hunyuan_video.md)も参照してください。 + +この機能は実験的なものです。 + +
+ +## Download the model / モデルのダウンロード + +You need to download the DiT, VAE, and Text Encoder (Qwen3) models. + +*As of January 2026, the base model has been released. VAE and Text Encoder are the same as the Turbo model, so if you have already downloaded them, there is no need to download them again.* + +The base version DiT, VAE, and Text Encoder can be obtained from Tongyi-MAI's official repository or ComfyUI weights. You can use either of the following: + +- **Official Repository**: [Tongyi-MAI/Z-Image](https://huggingface.co/Tongyi-MAI/Z-Image/) + - For DiT and Text Encoder, download all the split files and specify the first file (e.g., `00001-of-00002.safetensors`) in the arguments. + - You do not need to download files other than `*.safetensors`. +- **ComfyUI Weights**: [Comfy-Org/z_image](https://huggingface.co/Comfy-Org/z_image) + +You need to prepare the following models: + +- **DiT**: The transformer model. +- **VAE**: The autoencoder model. +- **Text Encoder**: Qwen3 model. + +*The following information is prior to the base model release. Since the base model has been released, it is recommended to use the base model for training.* + +> If you train Turbo model, it is recommended to use AI Toolkit/ostris's De-Turbo model. Download `z_image_de_turbo_v1_bf16.safetensors` from [ostris/Z-Image-De-Turbo](https://huggingface.co/ostris/Z-Image-De-Turbo) and use it as the DiT model. +> +> As another option, you can also use ostris's [ostris/zimage_turbo_training_adapter](https://huggingface.co/ostris/zimage_turbo_training_adapter) to train by combining the Turbo version with an adapter. In this case, download `zimage_turbo_training_adapter_v2.safetensors`, etc., and specify this LoRA weight in the `--base_weights` option during training. +> +> We would like to express our deep gratitude to ostris for providing the De-Turbo model and Training Adapter. + +
+日本語 + +DiT, VAE, Text Encoder (Qwen3) のモデルをダウンロードする必要があります。 + +*※2026/1:Baseモデルがリリースされました。VAEとText EncoderはTurboモデルと同じですので、ダウンロード済みの場合は再ダウンロードの必要はありません。* + +Base版のDiT、VAEとText EncoderはTongyi-MAIの公式リポジトリまたはComfyUI用重みから取得できます。以下のいずれかを使用してください: + +- **公式リポジトリ**: [Tongyi-MAI/Z-Image](https://huggingface.co/Tongyi-MAI/Z-Image/) + - DiT、Text Encoderは、分割された複数のファイルをすべてダウンロードし、引数には `00001-of-00002.safetensors` のような最初のファイルを指定してください。 + - `*.safetensors` ファイル以外はダウンロードする必要はありません。 +- **ComfyUI用重み**: [Comfy-Org/z_image](https://huggingface.co/Comfy-Org/z_image) + +以下のモデルを準備してください: + +- **DiT**: Transformerモデル。 +- **VAE**: Autoencoderモデル。 +- **Text Encoder**: Qwen3モデル。 + +*以下はBaseモデルリリース前の情報です。Baseモデルがリリースされたため、学習にはBaseモデルの使用をお勧めします。* + +> Turboモデルの学習を行う場合は、AI Toolkit/ostris氏のDe-Turboモデルを使用することをお勧めします。[ostris/Z-Image-De-Turbo](https://huggingface.co/ostris/Z-Image-De-Turbo) から `z_image_de_turbo_v1_bf16.safetensors` をダウンロードし、DiTモデルとして使用してください。 +> +> 別のオプションとして、ostris氏の [ostris/zimage_turbo_training_adapter](https://huggingface.co/ostris/zimage_turbo_training_adapter) を使用して、Turbo版とAdapterを組み合わせて学習することもできます。この場合は、`zimage_turbo_training_adapter_v2.safetensors` 等をダウンロードし、学習時に `--base_weights` オプションにこのLoRA重みを指定してください。 +> +> De-TurboモデルおよびTraining Adapterを提供してくださった ostris 氏に深く感謝します。 + +
+ +## Pre-caching / 事前キャッシング + +### Latent Pre-caching / latentの事前キャッシング + +Latent pre-caching uses a dedicated script for Z-Image. + +```bash +python src/musubi_tuner/zimage_cache_latents.py \ + --dataset_config path/to/toml \ + --vae path/to/vae_model +``` + +- Uses `zimage_cache_latents.py`. +- The dataset should be an image dataset. +- Z-Image does not support control images, so only target image latents are cached. + +
+日本語 + +latentの事前キャッシングはZ-Image専用のスクリプトを使用します。 + +- `zimage_cache_latents.py`を使用します。 +- データセットは画像データセットである必要があります。 +- Z-Imageはコントロール画像をサポートしていないため、ターゲット画像のlatentのみがキャッシュされます。 + +
+ +### Text Encoder Output Pre-caching / テキストエンコーダー出力の事前キャッシング + +Text encoder output pre-caching also uses a dedicated script. + +```bash +python src/musubi_tuner/zimage_cache_text_encoder_outputs.py \ + --dataset_config path/to/toml \ + --text_encoder path/to/text_encoder \ + --batch_size 16 +``` + +- Uses `zimage_cache_text_encoder_outputs.py`. +- Requires `--text_encoder` (Qwen3). +- Use `--fp8_llm` option to run the Text Encoder in fp8 mode for VRAM savings. +- Larger batch sizes require more VRAM. Adjust `--batch_size` according to your VRAM capacity. + +
+日本語 + +テキストエンコーダー出力の事前キャッシングも専用のスクリプトを使用します。 + +- `zimage_cache_text_encoder_outputs.py`を使用します。 +- `--text_encoder`(Qwen3)が必要です。 +- テキストエンコーダーをfp8モードで実行するための`--fp8_llm`オプションを使用することでVRAMを節約できます。 +- バッチサイズが大きいほど、より多くのVRAMが必要です。VRAM容量に応じて`--batch_size`を調整してください。 + +
+ +## Training / 学習 + +Training uses a dedicated script `zimage_train_network.py`. + +```bash +accelerate launch --num_cpu_threads_per_process 1 --mixed_precision bf16 src/musubi_tuner/zimage_train_network.py \ + --dit path/to/dit_model \ + --vae path/to/vae_model \ + --text_encoder path/to/text_encoder \ + --dataset_config path/to/toml \ + --sdpa --mixed_precision bf16 \ + --timestep_sampling shift --weighting_scheme none --discrete_flow_shift 2.0 \ + --optimizer_type adamw8bit --learning_rate 1e-4 --gradient_checkpointing \ + --max_data_loader_n_workers 2 --persistent_data_loader_workers \ + --network_module networks.lora_zimage --network_dim 32 \ + --max_train_epochs 16 --save_every_n_epochs 1 --seed 42 \ + --output_dir path/to/output_dir --output_name name-of-lora +``` + +- Uses `zimage_train_network.py`. +- **Requires** specifying `--vae` and `--text_encoder`. +- **Requires** specifying `--network_module networks.lora_zimage`. +- It is not yet clear whether `--mixed_precision bf16` or `fp16` is better for Z-Image training. +- The timestep sampling settings for Z-Image training are unclear, but it may be good to base them on `--timestep_sampling shift --weighting_scheme none --discrete_flow_shift 2.0` and adjust as needed. +- Memory saving options like `--fp8_base` and `--fp8_scaled` (for DiT) and `--fp8_llm` (for Text Encoder) are available. +- `--gradient_checkpointing` is available for memory savings. See [HunyuanVideo documentation](./hunyuan_video.md#memory-optimization) for details. + +
+日本語 + +Z-Imageの学習は専用のスクリプト`zimage_train_network.py`を使用します。 + +コマンド例は英語版を参照してください。 + +- `zimage_train_network.py`を使用します。 +- `--vae`、`--text_encoder`を指定する必要があります。 +- `--network_module networks.lora_zimage`を指定する必要があります。 +- Z-Imageの学習に`--mixed_precision bf16`と`fp16`のどちらが良いかはまだ不明です。 +- Z-Imageのタイムステップサンプリング設定は不明ですが、`--timestep_sampling shift --weighting_scheme none --discrete_flow_shift 2.0`をベースに調整すると良いかもしれません。 +- `--fp8_base`、`--fp8_scaled`(DiT用)や`--fp8_llm`(テキストエンコーダー用)などのメモリ節約オプションが利用可能です。 +- メモリ節約のために`--gradient_checkpointing`が利用可能です。詳細は[HunyuanVideoドキュメント](./hunyuan_video.md#memory-optimization)を参照してください。 + +
+ +### Converting LoRA weights to Diffusers format for ComfyUI / LoRA重みをComfyUIで使用可能なDiffusers形式に変換する + +A script is provided to convert Z-Image LoRA weights to Diffusers format for ComfyUI. LoHa and LoKr formats are supported. + +```bash +python src/musubi_tuner/networks/convert_lora.py \ + --input path/to/zimage_lora.safetensors \ + --output path/to/output_diffusers_lora.safetensors \ + --target other +``` + +- The script is `convert_lora.py`. +- `--input` argument is the input Z-Image LoRA weights file. +- `--output` argument is the output Diffusers format LoRA weights file. +- `--target other` means Diffusers format can be used in ComfyUI. + +`networks\convert_z_image_lora_to_comfy.py` can also be used for this purpose, but the converted weights may not work correctly with nunchaku. + +
+日本語 + +Z-ImageのLoRA重みをComfyUIで使用できるDiffusers形式に変換するスクリプトが提供されています。 + +- スクリプトは`convert_lora.py`です。 +- `--input`引数は入力のZ-Image LoRA重みファイルです。 +- `--output`引数は出力のDiffusers形式のLoRA重みファイルです。 +- `--target other`はComfyUIで使用できるDiffusers形式を意味します。 + +`networks\convert_z_image_lora_to_comfy.py`もこの目的で使用できますが、変換された重みがnunchakuで正しく動作しない可能性があります。 + +
+ +### Memory Optimization + +- `--fp8_base` and `--fp8_scaled` options are available to reduce memory usage of DiT (specify both together). Quality may degrade slightly. +- `--fp8_llm` option is available to reduce memory usage of Text Encoder (Qwen3). +- `--gradient_checkpointing` and `--gradient_checkpointing_cpu_offload` are available for memory savings. See [HunyuanVideo documentation](./hunyuan_video.md#memory-optimization) for details. +- `--blocks_to_swap` option is available to offload some blocks to CPU. The maximum number of blocks that can be offloaded is 28. + +
+日本語 + +- DiTのメモリ使用量を削減するために、`--fp8_base`と`--fp8_scaled`オプションを指定可能です(同時に指定してください)。品質はやや低下する可能性があります。 +- Text Encoder (Qwen3)のメモリ使用量を削減するために、`--fp8_llm`オプションを指定可能です。 +- メモリ節約のために`--gradient_checkpointing`と`--gradient_checkpointing_cpu_offload`が利用可能です。詳細は[HunyuanVideoドキュメント](./hunyuan_video.md#memory-optimization)を参照してください。 +- `--blocks_to_swap`オプションで、一部のブロックをCPUにオフロードできます。オフロード可能な最大ブロック数は28です。 + +
+ +### Attention + +- `--sdpa` for PyTorch's scaled dot product attention (does not require additional dependencies). +- `--flash_attn` for [FlashAttention](https://github.com/Dao-AILab/flash-attention). +- `--xformers` for xformers (requires `--split_attn`). +- `--sage_attn` for SageAttention (not yet supported for training). +- `--split_attn` processes attention in chunks, reducing VRAM usage slightly. + +
+日本語 + +- `--sdpa`でPyTorchのscaled dot product attentionを使用(追加の依存ライブラリを必要としません)。 +- `--flash_attn`で[FlashAttention](https://github.com/Dao-AILab/flash-attention)を使用。 +- `--xformers`でxformersの利用も可能(`--split_attn`が必要)。 +- `--sage_attn`でSageAttentionを使用(現時点では学習に未対応)。 +- `--split_attn`を指定すると、attentionを分割して処理し、VRAM使用量をわずかに減らします。 + +
+ +### Sample images during training with De-Turbo model or Training Adapter / De-TurboモデルまたはTraining Adapterで学習中にサンプル画像を生成する + +When training with the De-Turbo model or Training Adapter, add negative prompt and CFG scale to the sampling options to generate sample images with CFG. It is also recommended to increase the number of steps. `--l` specifies the CFG scale (default 4). + +```text +A beautiful landscape painting of mountains during sunset. --n bad quality --w 1280 --h 720 --fs 3 --s 20 --d 1234 --l 4 +``` + +
+日本語 + + De-TurboモデルまたはTraining Adapterで学習する場合、サンプリングオプションにネガティブプロンプトとCFGスケールを追加して、CFGありでサンプル画像を生成してください。またステップ数も増やすことをお勧めします。`--l`でCFGスケールを指定します(デフォルトは4です)。 + + ```text +A beautiful landscape painting of mountains during sunset. --n bad quality --w 1280 --h 720 --fs 3 --s 20 --d 1234 --l 4 +``` + +
+ +## Finetuning + +Finetuning uses a dedicated script `zimage_train.py`. This script performs full finetuning of the model, not LoRA. Sample usage is as follows: + +```bash +accelerate launch --num_cpu_threads_per_process 1 src/musubi_tuner/zimage_train.py \ + --dit path/to/dit_model \ + --vae path/to/vae_model \ + --text_encoder path/to/text_encoder \ + --dataset_config path/to/toml \ + --sdpa --mixed_precision bf16 --gradient_checkpointing \ + --optimizer_type adafactor --learning_rate 1e-6 --fused_backward_pass \ + --optimizer_args "relative_step=False" "scale_parameter=False" "warmup_init=False" \ + --max_grad_norm 0 --lr_scheduler constant_with_warmup --lr_warmup_steps 10 \ + --max_data_loader_n_workers 2 --persistent_data_loader_workers \ + --max_train_epochs 16 --save_every_n_epochs 1 --seed 42 \ + --output_dir path/to/output_dir --output_name name-of-model +``` + +- Uses `zimage_train.py`. +- Finetuning requires a large amount of VRAM. The use of memory saving options is strongly recommended. +- `--full_bf16`: Loads the model weights in bfloat16 format to significantly reduce VRAM usage. +- `--optimizer_type adafactor`: Using Adafactor is recommended for finetuning. +- `--fused_backward_pass`: Reduces VRAM usage during the backward pass when using Adafactor. +- `--mem_eff_save`: Reduces main memory (RAM) usage when saving checkpoints. +- `--blocks_to_swap`: Swaps model blocks between VRAM and main memory to reduce VRAM usage. This is effective when VRAM is limited. +- `--disable_numpy_memmap`: Disables numpy memory mapping for model loading, loading with standard file read. Increases RAM usage but may speed up model loading in some cases. +- `--block_swap_optimizer_patch_params` option is available to patch optimizer parameters for block swapping. + +`--full_bf16` reduces VRAM usage by about 30GB but may impact model accuracy as the weights are kept in bfloat16. Note that the optimizer state is still kept in float32. In addition, it is recommended to use this with an optimizer that supports stochastic rounding. In this repository, Adafactor optimizer with `--fused_backward_pass` option supports stochastic rounding. + +`--block_swap_optimizer_patch_params` option moves the gradients to the same device as the parameters during the optimizer step, which makes it work with block swapping. This workaround currently works with AdamW and Adafactor etc. AdamW8bit and other optimizers do not work with this patch due to their specific implementation. + +When using `--mem_eff_save`, please note that traditional saving methods are still used when saving the optimizer state in `--save_state`, requiring about 20GB of main memory. + +### Recommended Settings + +We are still exploring the optimal settings. The configurations above are just examples, so please adjust them as needed. We welcome your feedback. + +If you have ample VRAM, you can use any optimizer of your choice. `--full_bf16` is not recommended. + +For limited VRAM environments (e.g., 48GB or less), you can use one of the following options: + +1. Use `--blocks_to_swap` + `--block_swap_optimizer_patch_params` + compatible optimizer. +2. Use `--blocks_to_swap` + Adafactor + `--fused_backward_pass`. +3. Use `--full_bf16` + Adafactor optimizer + `--fused_backward_pass`. +4. Use `--blocks_to_swap` + `--full_bf16` + Adafactor optimizer + `--fused_backward_pass`. + +VRAM usage decreases in the order of 1. to 4. (4. being the least). The time taken for training increases in the order of 2. = 3. < 4. < 1. (1. being the slowest). The expected accuracy is in the order of 1. > 2. > 3. = 4. (1. being the highest). + +The sample configuration is a recommended setting when using option 3. If VRAM is further constrained, you can also use option 4. Adjust `--lr_warmup_steps` to a value between about 10 and 100. + +`--fused_backward_pass` currently does not support gradient accumulation. Also, since max grad norm may not work as expected, it is recommended to specify `--max_grad_norm 0`. + +Experience with other models suggests that the learning rate may need to be reduced significantly; something in the range of 1e-6 to 1e-5 might be a good place to start. + +
+日本語 + +Finetuningは専用のスクリプト`zimage_train.py`を使用します。このスクリプトはLoRAではなく、モデル全体のfinetuningを行います。 + +- `zimage_train.py`を使用します。 +- Finetuningは大量のVRAMを必要とします。メモリ節約オプションの使用を強く推奨します。 +- `--full_bf16`: モデルの重みをbfloat16形式で読み込み、VRAM使用量を大幅に削減します。 +- `--optimizer_type adafactor`: FinetuningではAdafactorの使用が推奨されます。 +- `--fused_backward_pass`: Adafactor使用時に、backward pass中のVRAM使用量を削減します。 +- `--mem_eff_save`: チェックポイント保存時のメインメモリ(RAM)使用量を削減します。 +- `--blocks_to_swap`: モデルのブロックをVRAMとメインメモリ間でスワップし、VRAM使用量を削減します。VRAMが少ない場合に有効です。 +- `--disable_numpy_memmap`: モデル読み込み時のnumpyメモリマッピングを無効化し、標準のファイル読み込みで読み込みを行います。RAM使用量は増加しますが、場合によってはモデルの読み込みが高速化されます。 +- `--block_swap_optimizer_patch_params`: ブロックスワッピングのためのオプティマイザパラメータをパッチするためのオプションです。 + +`--full_bf16`はVRAM使用量を約30GB削減しますが、重みがbfloat16で保持されるため、モデルの精度に影響を与える可能性があります。オプティマイザの状態はfloat32で保持されます。また、効率的な学習のために、stochastic roundingをサポートするオプティマイザとの併用が推奨されます。このリポジトリでは、`adafactor`オプティマイザに`--fused_backward_pass`オプションの組み合わせでstochastic roundingをサポートしています。 + +`--block_swap_optimizer_patch_params`オプションにより、オプティマイザステップ中に勾配がパラメータと同じデバイスに移動され、ブロックスワッピングで動作するようになります。この回避策は現在AdamWやAdafactorなどで動作します。オプティマイザの実装に依存するため、AdamW8bitやその他のオプティマイザはこのパッチでは動作しません。 + +`--mem_eff_save`を使用する場合でも、`--save_state`においてはオプティマイザの状態を保存する際に従来の保存方法が依然として使用されるため、約20GBのメインメモリが必要であることに注意してください。 + +### 推奨設定 + +最適な設定はまだ調査中です。上記の構成はあくまで一例ですので、必要に応じて調整してください。フィードバックをお待ちしております。 + +十分なVRAMがある場合は、お好みのオプティマイザを使用できます。`--full_bf16`は推奨されません。 + +VRAMが限られている環境(例:48GB以下)の場合は、次のいずれかのオプションを利用できます。 + +1. `--blocks_to_swap`+`--block_swap_optimizer_patch_params`+互換性のあるオプティマイザを使用する。 +2. `--blocks_to_swap`+Adafactor+`--fused_backward_pass`を使用する。 +3. `--full_bf16`+Adafactorオプティマイザ+`--fused_backward_pass`を使用する。 +4. `--blocks_to_swap`+`--full_bf16`+Adafactorオプティマイザ+`--fused_backward_pass`を使用する。 + +VRAM使用量は1.から4.の順で減少します(4.が最も少ない)。学習にかかる時間は2.=3. < 4. < 1.の順で長くなります(1.が最も遅い)。期待される精度は、1. > 2. > 3. = 4.の順になります(1.が最も高い)。 + +サンプルの設定は、3.のオプションを使用する場合の推奨設定です。VRAMがさらに制約されている場合は、4.のオプションを使用することもできます。`--lr_warmup_steps`は約10から100の間の値に調整してください。 + +現時点では`--fused_backward_pass`はgradient accumulationに対応していません。またmax grad normも想定通りに動作しない可能性があるため、`--max_grad_norm 0`を指定することを推奨します。 + +他のモデルでの経験則では、学習率は大幅に減らす必要があるかもしれません。1e-6から1e-5の範囲で試してみると良いでしょう。 + +
+ +## Inference / 推論 + +Inference uses a dedicated script `zimage_generate_image.py`. + +```bash +python src/musubi_tuner/zimage_generate_image.py \ + --dit path/to/dit_model \ + --vae path/to/vae_model \ + --text_encoder path/to/text_encoder \ + --prompt "A cat" \ + --image_size 1024 1024 --infer_steps 25 \ + --flow_shift 3.0 --guidance_scale 0.0 \ + --attn_mode torch \ + --save_path path/to/save/dir \ + --seed 1234 --lora_multiplier 1.0 --lora_weight path/to/lora.safetensors +``` + +- Uses `zimage_generate_image.py`. +- `--flow_shift` defaults to 3.0. +- `--guidance_scale` defaults to 0.0 (no classifier-free guidance, for Turbo model). Specify a positive value to enable CFG (4.0 is the offcial default for Base model). +- `--fp8` and `--fp8_scaled` options are available for DiT. +- `--fp8_llm` option is available for Text Encoder. + +
+日本語 + +推論は専用のスクリプト`zimage_generate_image.py`を使用します。 + +コマンド例は英語版を参照してください。 + +- `zimage_generate_image.py`を使用します。 +- `--flow_shift`のデフォルトは3.0です。 +- `--guidance_scale`のデフォルトは0.0(Classifier-Free Guidanceなし、Turboモデル用)です。正の値を指定するとCFGが有効になります(Baseモデルの公式デフォルトは4.0です)。 +- `--fp8`および`--fp8_scaled`オプションがDiTで利用可能です。 +- `--fp8_llm`オプションがテキストエンコーダーで利用可能です。 +- `--blocks_to_swap`オプションで、一部のブロックをCPUにオフロードできます。オフロード可能な最大ブロック数は28です。 +- LoRAの読み込みオプション(`--lora_weight`、`--lora_multiplier`、`--include_patterns`、`--exclude_patterns`)が利用可能です。LyCORISもサポートされています。 +- `--save_merged_model`オプションは、LoRAの重みをマージした後にDiTモデルを保存するためのオプションです。これを指定すると推論はスキップされます。 + +
diff --git a/VRGDG_Musubi-tuner/flux_2_cache_latents.py b/VRGDG_Musubi-tuner/flux_2_cache_latents.py new file mode 100644 index 0000000000000000000000000000000000000000..e7cd5f814bacd46f0d50c3380095b28b83823264 --- /dev/null +++ b/VRGDG_Musubi-tuner/flux_2_cache_latents.py @@ -0,0 +1,4 @@ +from musubi_tuner.flux_2_cache_latents import main + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/flux_2_cache_text_encoder_outputs.py b/VRGDG_Musubi-tuner/flux_2_cache_text_encoder_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..4478058e045eea4a02191f05f84d57f18789c2fe --- /dev/null +++ b/VRGDG_Musubi-tuner/flux_2_cache_text_encoder_outputs.py @@ -0,0 +1,4 @@ +from musubi_tuner.flux_2_cache_text_encoder_outputs import main + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/flux_2_generate_image.py b/VRGDG_Musubi-tuner/flux_2_generate_image.py new file mode 100644 index 0000000000000000000000000000000000000000..5da5b54835051da691a4e5fb225095ae55c7ecb5 --- /dev/null +++ b/VRGDG_Musubi-tuner/flux_2_generate_image.py @@ -0,0 +1,4 @@ +from musubi_tuner.flux_2_generate_image import main + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/flux_2_train_network.py b/VRGDG_Musubi-tuner/flux_2_train_network.py new file mode 100644 index 0000000000000000000000000000000000000000..36c4fc53cd3b90e28467557b9fb88e83a7191c60 --- /dev/null +++ b/VRGDG_Musubi-tuner/flux_2_train_network.py @@ -0,0 +1,4 @@ +from musubi_tuner.flux_2_train_network import main + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/flux_kontext_cache_latents.py b/VRGDG_Musubi-tuner/flux_kontext_cache_latents.py new file mode 100644 index 0000000000000000000000000000000000000000..cf64871787be00ad4c4ac2f63279655a1717c841 --- /dev/null +++ b/VRGDG_Musubi-tuner/flux_kontext_cache_latents.py @@ -0,0 +1,4 @@ +from musubi_tuner.flux_kontext_cache_latents import main + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/flux_kontext_cache_text_encoder_outputs.py b/VRGDG_Musubi-tuner/flux_kontext_cache_text_encoder_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..79dbbafc60db1bd9110a896b1c0d83b48df39ebb --- /dev/null +++ b/VRGDG_Musubi-tuner/flux_kontext_cache_text_encoder_outputs.py @@ -0,0 +1,4 @@ +from musubi_tuner.flux_kontext_cache_text_encoder_outputs import main + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/flux_kontext_generate_image.py b/VRGDG_Musubi-tuner/flux_kontext_generate_image.py new file mode 100644 index 0000000000000000000000000000000000000000..35225c1bef4a6b9319f1d145d034310a1ec71817 --- /dev/null +++ b/VRGDG_Musubi-tuner/flux_kontext_generate_image.py @@ -0,0 +1,4 @@ +from musubi_tuner.flux_kontext_generate_image import main + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/flux_kontext_train_network.py b/VRGDG_Musubi-tuner/flux_kontext_train_network.py new file mode 100644 index 0000000000000000000000000000000000000000..3c64848181669602de2cecf69a31fb74e1ebad88 --- /dev/null +++ b/VRGDG_Musubi-tuner/flux_kontext_train_network.py @@ -0,0 +1,4 @@ +from musubi_tuner.flux_kontext_train_network import main + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/fpack_cache_latents.py b/VRGDG_Musubi-tuner/fpack_cache_latents.py new file mode 100644 index 0000000000000000000000000000000000000000..89098570d44bbe33ce673161f067648912f3e570 --- /dev/null +++ b/VRGDG_Musubi-tuner/fpack_cache_latents.py @@ -0,0 +1,4 @@ +from musubi_tuner.fpack_cache_latents import main + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/fpack_cache_text_encoder_outputs.py b/VRGDG_Musubi-tuner/fpack_cache_text_encoder_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..ccfae7454c15b1e58a77ad9679a18188c9a7739f --- /dev/null +++ b/VRGDG_Musubi-tuner/fpack_cache_text_encoder_outputs.py @@ -0,0 +1,4 @@ +from musubi_tuner.fpack_cache_text_encoder_outputs import main + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/fpack_generate_video.py b/VRGDG_Musubi-tuner/fpack_generate_video.py new file mode 100644 index 0000000000000000000000000000000000000000..6515d248b4fdc045310a15287cbaad2fe80eec26 --- /dev/null +++ b/VRGDG_Musubi-tuner/fpack_generate_video.py @@ -0,0 +1,4 @@ +from musubi_tuner.fpack_generate_video import main + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/fpack_train_network.py b/VRGDG_Musubi-tuner/fpack_train_network.py new file mode 100644 index 0000000000000000000000000000000000000000..ad03707e043599e2e47e28a7fec07b3732fe4d82 --- /dev/null +++ b/VRGDG_Musubi-tuner/fpack_train_network.py @@ -0,0 +1,4 @@ +from musubi_tuner.fpack_train_network import main + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/hv_1_5_cache_latents.py b/VRGDG_Musubi-tuner/hv_1_5_cache_latents.py new file mode 100644 index 0000000000000000000000000000000000000000..3a1b8e3ba4178310831ad791c95435e23ae684f9 --- /dev/null +++ b/VRGDG_Musubi-tuner/hv_1_5_cache_latents.py @@ -0,0 +1,4 @@ +from musubi_tuner.hv_1_5_cache_latents import main + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/hv_1_5_cache_text_encoder_outputs.py b/VRGDG_Musubi-tuner/hv_1_5_cache_text_encoder_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..0df4a59f434efc3dd9071e202b11f110d3debdbf --- /dev/null +++ b/VRGDG_Musubi-tuner/hv_1_5_cache_text_encoder_outputs.py @@ -0,0 +1,4 @@ +from musubi_tuner.hv_1_5_cache_text_encoder_outputs import main + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/hv_1_5_generate_video.py b/VRGDG_Musubi-tuner/hv_1_5_generate_video.py new file mode 100644 index 0000000000000000000000000000000000000000..cc81b0b0e7d752b1a43b0b30ab9ca24a9da49a9e --- /dev/null +++ b/VRGDG_Musubi-tuner/hv_1_5_generate_video.py @@ -0,0 +1,4 @@ +from musubi_tuner.hv_1_5_generate_video import main + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/hv_1_5_train_network.py b/VRGDG_Musubi-tuner/hv_1_5_train_network.py new file mode 100644 index 0000000000000000000000000000000000000000..056fe9ac349b8d97e495bf52d49a645da64f3ca5 --- /dev/null +++ b/VRGDG_Musubi-tuner/hv_1_5_train_network.py @@ -0,0 +1,4 @@ +from musubi_tuner.hv_1_5_train_network import main + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/hv_generate_video.py b/VRGDG_Musubi-tuner/hv_generate_video.py new file mode 100644 index 0000000000000000000000000000000000000000..77a662bcd580f1a6fc35ea4318eb5c2866f1ec08 --- /dev/null +++ b/VRGDG_Musubi-tuner/hv_generate_video.py @@ -0,0 +1,4 @@ +from musubi_tuner.hv_generate_video import main + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/hv_train.py b/VRGDG_Musubi-tuner/hv_train.py new file mode 100644 index 0000000000000000000000000000000000000000..0ce30c77e103eff59d600f21efc7f37d3a30027f --- /dev/null +++ b/VRGDG_Musubi-tuner/hv_train.py @@ -0,0 +1,4 @@ +from musubi_tuner.hv_train import main + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/hv_train_network.py b/VRGDG_Musubi-tuner/hv_train_network.py new file mode 100644 index 0000000000000000000000000000000000000000..a9428cc2d56b96438ccac11216196413bc689d86 --- /dev/null +++ b/VRGDG_Musubi-tuner/hv_train_network.py @@ -0,0 +1,4 @@ +from musubi_tuner.hv_train_network import main + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/images/logo_aihub.png b/VRGDG_Musubi-tuner/images/logo_aihub.png new file mode 100644 index 0000000000000000000000000000000000000000..0b41f5f72c7f3512ce4bf3d3c16dba27b823e71f --- /dev/null +++ b/VRGDG_Musubi-tuner/images/logo_aihub.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:13f8b7aea1907b42936cfad5889e80337486402e10e9f5719c29f019a10f8965 +size 7090 diff --git a/VRGDG_Musubi-tuner/kandinsky5_cache_latents.py b/VRGDG_Musubi-tuner/kandinsky5_cache_latents.py new file mode 100644 index 0000000000000000000000000000000000000000..154944795aefd9fbd5b092cae5515c3cf6934c67 --- /dev/null +++ b/VRGDG_Musubi-tuner/kandinsky5_cache_latents.py @@ -0,0 +1,4 @@ +from musubi_tuner.kandinsky5_cache_latents import main + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/kandinsky5_cache_text_encoder_outputs.py b/VRGDG_Musubi-tuner/kandinsky5_cache_text_encoder_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..740096d8ea96f5fb165031b6aa2d1014f3bbab87 --- /dev/null +++ b/VRGDG_Musubi-tuner/kandinsky5_cache_text_encoder_outputs.py @@ -0,0 +1,4 @@ +from musubi_tuner.kandinsky5_cache_text_encoder_outputs import main + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/kandinsky5_generate_video.py b/VRGDG_Musubi-tuner/kandinsky5_generate_video.py new file mode 100644 index 0000000000000000000000000000000000000000..7d054d3e2b9f299785420f5b8d61979c36257abf --- /dev/null +++ b/VRGDG_Musubi-tuner/kandinsky5_generate_video.py @@ -0,0 +1,4 @@ +from musubi_tuner.kandinsky5_generate_video import main + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/kandinsky5_train_network.py b/VRGDG_Musubi-tuner/kandinsky5_train_network.py new file mode 100644 index 0000000000000000000000000000000000000000..b43eb9dc704d0a916b8cb1bf32ec017e7dab2e9e --- /dev/null +++ b/VRGDG_Musubi-tuner/kandinsky5_train_network.py @@ -0,0 +1,4 @@ +from musubi_tuner.kandinsky5_train_network import main + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/lora_post_hoc_ema.py b/VRGDG_Musubi-tuner/lora_post_hoc_ema.py new file mode 100644 index 0000000000000000000000000000000000000000..87dedf0a4981522ccbc482645005ef93230e32c3 --- /dev/null +++ b/VRGDG_Musubi-tuner/lora_post_hoc_ema.py @@ -0,0 +1,4 @@ +from musubi_tuner.lora_post_hoc_ema import main + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/ltx2_cache_dino_features.py b/VRGDG_Musubi-tuner/ltx2_cache_dino_features.py new file mode 100644 index 0000000000000000000000000000000000000000..7a1a629a91c2276cf66fb9f7d14abc85d1427ae8 --- /dev/null +++ b/VRGDG_Musubi-tuner/ltx2_cache_dino_features.py @@ -0,0 +1,4 @@ +from musubi_tuner.ltx2_cache_dino_features import main + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/ltx2_cache_latents.py b/VRGDG_Musubi-tuner/ltx2_cache_latents.py new file mode 100644 index 0000000000000000000000000000000000000000..d659db3bc52dd749acf11632d11f2c638e6fbd52 --- /dev/null +++ b/VRGDG_Musubi-tuner/ltx2_cache_latents.py @@ -0,0 +1,4 @@ +from musubi_tuner.ltx2_cache_latents import main + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/ltx2_cache_text_encoder_outputs.py b/VRGDG_Musubi-tuner/ltx2_cache_text_encoder_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..8eaff15a782874d506417ef19ff5c22f7db8193c --- /dev/null +++ b/VRGDG_Musubi-tuner/ltx2_cache_text_encoder_outputs.py @@ -0,0 +1,4 @@ +from musubi_tuner.ltx2_cache_text_encoder_outputs import main + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/ltx2_estimate.py b/VRGDG_Musubi-tuner/ltx2_estimate.py new file mode 100644 index 0000000000000000000000000000000000000000..10176fe8230d7d222c0986b464591a216fbc2a5a --- /dev/null +++ b/VRGDG_Musubi-tuner/ltx2_estimate.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python3 +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent / "src")) + +from musubi_tuner.ltx2_estimate import main + + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/ltx2_generate_video.py b/VRGDG_Musubi-tuner/ltx2_generate_video.py new file mode 100644 index 0000000000000000000000000000000000000000..45454ce4de8264d249516d846bf6839e9f7267a3 --- /dev/null +++ b/VRGDG_Musubi-tuner/ltx2_generate_video.py @@ -0,0 +1,4 @@ +from musubi_tuner.ltx2_generate_video import main + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/ltx2_merge_lora.py b/VRGDG_Musubi-tuner/ltx2_merge_lora.py new file mode 100644 index 0000000000000000000000000000000000000000..6cf7b1d64bf0a8201da37b72c19b40a81df69d82 --- /dev/null +++ b/VRGDG_Musubi-tuner/ltx2_merge_lora.py @@ -0,0 +1,5 @@ +from musubi_tuner.ltx2_merge_lora import main + + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/ltx2_merge_lora_to_model.py b/VRGDG_Musubi-tuner/ltx2_merge_lora_to_model.py new file mode 100644 index 0000000000000000000000000000000000000000..b3ec8182689926a7581beed2d49b6f5d8e4a8f46 --- /dev/null +++ b/VRGDG_Musubi-tuner/ltx2_merge_lora_to_model.py @@ -0,0 +1,5 @@ +from musubi_tuner.ltx2_merge_lora_to_model import main + + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/ltx2_train.py b/VRGDG_Musubi-tuner/ltx2_train.py new file mode 100644 index 0000000000000000000000000000000000000000..426ede7c134e35dab5e8f0550b37e743f00edfc2 --- /dev/null +++ b/VRGDG_Musubi-tuner/ltx2_train.py @@ -0,0 +1,6 @@ +#!/usr/bin/env python3 +from musubi_tuner.ltx2_train import main + + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/ltx2_train_network.py b/VRGDG_Musubi-tuner/ltx2_train_network.py new file mode 100644 index 0000000000000000000000000000000000000000..38e1860c3effd4809e83d6786618df1fc833b2ac --- /dev/null +++ b/VRGDG_Musubi-tuner/ltx2_train_network.py @@ -0,0 +1,4 @@ +from musubi_tuner.ltx2_train_network import main + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/ltx2_train_slider.py b/VRGDG_Musubi-tuner/ltx2_train_slider.py new file mode 100644 index 0000000000000000000000000000000000000000..b15ddd282288f186fe47b90c828ae751ab51ee5f --- /dev/null +++ b/VRGDG_Musubi-tuner/ltx2_train_slider.py @@ -0,0 +1,6 @@ +#!/usr/bin/env python3 +from musubi_tuner.ltx2_train_slider import main + + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/ltx2_train_vae.py b/VRGDG_Musubi-tuner/ltx2_train_vae.py new file mode 100644 index 0000000000000000000000000000000000000000..0e0536da3e8d48a996344a8efde0139cb5b190b8 --- /dev/null +++ b/VRGDG_Musubi-tuner/ltx2_train_vae.py @@ -0,0 +1,5 @@ +from musubi_tuner.ltx2_train_vae import main + + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/merge_lora.py b/VRGDG_Musubi-tuner/merge_lora.py new file mode 100644 index 0000000000000000000000000000000000000000..dee3b3931bc51b26f302379938ecb2ea3c4b2835 --- /dev/null +++ b/VRGDG_Musubi-tuner/merge_lora.py @@ -0,0 +1,4 @@ +from musubi_tuner.merge_lora import main + +if __name__ == "__main__": + main() diff --git a/VRGDG_Musubi-tuner/models/gemma-3-12b-it/.gitattributes b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..3c4370fda8fab65837da0173e4e02cfa23e598b4 --- /dev/null +++ b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/.gitattributes @@ -0,0 +1,42 @@ +*.7z filter=lfs diff=lfs merge=lfs -text +*.arrow filter=lfs diff=lfs merge=lfs -text +*.bin filter=lfs diff=lfs merge=lfs -text +*.bz2 filter=lfs diff=lfs merge=lfs -text +*.ckpt filter=lfs diff=lfs merge=lfs -text +*.ftz filter=lfs diff=lfs merge=lfs -text +*.gz filter=lfs diff=lfs merge=lfs -text +*.h5 filter=lfs diff=lfs merge=lfs -text +*.joblib filter=lfs diff=lfs merge=lfs -text +*.lfs.* filter=lfs diff=lfs merge=lfs -text +*.mlmodel filter=lfs diff=lfs merge=lfs -text +*.model filter=lfs diff=lfs merge=lfs -text +*.msgpack filter=lfs diff=lfs merge=lfs -text +*.npy filter=lfs diff=lfs merge=lfs -text +*.npz filter=lfs diff=lfs merge=lfs -text +*.onnx filter=lfs diff=lfs merge=lfs -text +*.ot filter=lfs diff=lfs merge=lfs -text +*.parquet filter=lfs diff=lfs merge=lfs -text +*.pb filter=lfs diff=lfs merge=lfs -text +*.pickle filter=lfs diff=lfs merge=lfs -text +*.pkl filter=lfs diff=lfs merge=lfs -text +*.pt filter=lfs diff=lfs merge=lfs -text +*.pth filter=lfs diff=lfs merge=lfs -text +*.rar filter=lfs diff=lfs merge=lfs -text +*.safetensors filter=lfs diff=lfs merge=lfs -text +saved_model/**/* filter=lfs diff=lfs merge=lfs -text +*.tar.* filter=lfs diff=lfs merge=lfs -text +*.tar filter=lfs diff=lfs merge=lfs -text +*.tflite filter=lfs diff=lfs merge=lfs -text +*.tgz filter=lfs diff=lfs merge=lfs -text +*.wasm filter=lfs diff=lfs merge=lfs -text +*.xz filter=lfs diff=lfs merge=lfs -text +*.zip filter=lfs diff=lfs merge=lfs -text +*.zst filter=lfs diff=lfs merge=lfs -text +*tfevents* filter=lfs diff=lfs merge=lfs -text +tokenizer.json filter=lfs diff=lfs merge=lfs -text +model-00001-of-00005.safetensors filter=lfs diff=lfs merge=lfs -text +model-00002-of-00005.safetensors filter=lfs diff=lfs merge=lfs -text +model-00003-of-00005.safetensors filter=lfs diff=lfs merge=lfs -text +model-00004-of-00005.safetensors filter=lfs diff=lfs merge=lfs -text +model-00005-of-00005.safetensors filter=lfs diff=lfs merge=lfs -text +tokenizer.model filter=lfs diff=lfs merge=lfs -text diff --git a/VRGDG_Musubi-tuner/models/gemma-3-12b-it/README.md b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/README.md new file mode 100644 index 0000000000000000000000000000000000000000..83dba03ddca6dff78d9c0bb6f9f93bb8eabd6410 --- /dev/null +++ b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/README.md @@ -0,0 +1,535 @@ +--- +license: gemma +library_name: transformers +pipeline_tag: image-text-to-text +extra_gated_heading: Access Gemma on Hugging Face +extra_gated_prompt: To access Gemma on Hugging Face, you’re required to review and + agree to Google’s usage license. To do this, please ensure you’re logged in to Hugging + Face and click below. Requests are processed immediately. +extra_gated_button_content: Acknowledge license +base_model: google/gemma-3-12b-pt +--- + +# Gemma 3 model card + +**Model Page**: [Gemma](https://ai.google.dev/gemma/docs/core) + +**Resources and Technical Documentation**: + +* [Gemma 3 Technical Report][g3-tech-report] +* [Responsible Generative AI Toolkit][rai-toolkit] +* [Gemma on Kaggle][kaggle-gemma] +* [Gemma on Vertex Model Garden][vertex-mg-gemma3] + +**Terms of Use**: [Terms][terms] + +**Authors**: Google DeepMind + +## Model Information + +Summary description and brief definition of inputs and outputs. + +### Description + +Gemma is a family of lightweight, state-of-the-art open models from Google, +built from the same research and technology used to create the Gemini models. +Gemma 3 models are multimodal, handling text and image input and generating text +output, with open weights for both pre-trained variants and instruction-tuned +variants. Gemma 3 has a large, 128K context window, multilingual support in over +140 languages, and is available in more sizes than previous versions. Gemma 3 +models are well-suited for a variety of text generation and image understanding +tasks, including question answering, summarization, and reasoning. Their +relatively small size makes it possible to deploy them in environments with +limited resources such as laptops, desktops or your own cloud infrastructure, +democratizing access to state of the art AI models and helping foster innovation +for everyone. + +### Inputs and outputs + +- **Input:** + - Text string, such as a question, a prompt, or a document to be summarized + - Images, normalized to 896 x 896 resolution and encoded to 256 tokens + each + - Total input context of 128K tokens for the 4B, 12B, and 27B sizes, and + 32K tokens for the 1B size + +- **Output:** + - Generated text in response to the input, such as an answer to a + question, analysis of image content, or a summary of a document + - Total output context of 8192 tokens + +### Usage + +Below, there are some code snippets on how to get quickly started with running the model. First, install the Transformers library. Gemma 3 is supported starting from transformers 4.50.0. + +```sh +$ pip install -U transformers +``` + +Then, copy the snippet from the section that is relevant for your use case. + +#### Running with the `pipeline` API + +You can initialize the model and processor for inference with `pipeline` as follows. + +```python +from transformers import pipeline +import torch + +pipe = pipeline( + "image-text-to-text", + model="google/gemma-3-12b-it", + device="cuda", + torch_dtype=torch.bfloat16 +) +``` + +With instruction-tuned models, you need to use chat templates to process our inputs first. Then, you can pass it to the pipeline. + +```python +messages = [ + { + "role": "system", + "content": [{"type": "text", "text": "You are a helpful assistant."}] + }, + { + "role": "user", + "content": [ + {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"}, + {"type": "text", "text": "What animal is on the candy?"} + ] + } +] + +output = pipe(text=messages, max_new_tokens=200) +print(output[0]["generated_text"][-1]["content"]) +# Okay, let's take a look! +# Based on the image, the animal on the candy is a **turtle**. +# You can see the shell shape and the head and legs. +``` + +#### Running the model on a single / multi GPU + +```python +# pip install accelerate + +from transformers import AutoProcessor, Gemma3ForConditionalGeneration +from PIL import Image +import requests +import torch + +model_id = "google/gemma-3-12b-it" + +model = Gemma3ForConditionalGeneration.from_pretrained( + model_id, device_map="auto" +).eval() + +processor = AutoProcessor.from_pretrained(model_id) + +messages = [ + { + "role": "system", + "content": [{"type": "text", "text": "You are a helpful assistant."}] + }, + { + "role": "user", + "content": [ + {"type": "image", "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg"}, + {"type": "text", "text": "Describe this image in detail."} + ] + } +] + +inputs = processor.apply_chat_template( + messages, add_generation_prompt=True, tokenize=True, + return_dict=True, return_tensors="pt" +).to(model.device, dtype=torch.bfloat16) + +input_len = inputs["input_ids"].shape[-1] + +with torch.inference_mode(): + generation = model.generate(**inputs, max_new_tokens=100, do_sample=False) + generation = generation[0][input_len:] + +decoded = processor.decode(generation, skip_special_tokens=True) +print(decoded) + +# **Overall Impression:** The image is a close-up shot of a vibrant garden scene, +# focusing on a cluster of pink cosmos flowers and a busy bumblebee. +# It has a slightly soft, natural feel, likely captured in daylight. +``` + +### Citation + +```none +@article{gemma_2025, + title={Gemma 3}, + url={https://goo.gle/Gemma3Report}, + publisher={Kaggle}, + author={Gemma Team}, + year={2025} +} +``` + +## Model Data + +Data used for model training and how the data was processed. + +### Training Dataset + +These models were trained on a dataset of text data that includes a wide variety +of sources. The 27B model was trained with 14 trillion tokens, the 12B model was +trained with 12 trillion tokens, 4B model was trained with 4 trillion tokens and +1B with 2 trillion tokens. Here are the key components: + +- Web Documents: A diverse collection of web text ensures the model is + exposed to a broad range of linguistic styles, topics, and vocabulary. The + training dataset includes content in over 140 languages. +- Code: Exposing the model to code helps it to learn the syntax and + patterns of programming languages, which improves its ability to generate + code and understand code-related questions. +- Mathematics: Training on mathematical text helps the model learn logical + reasoning, symbolic representation, and to address mathematical queries. +- Images: A wide range of images enables the model to perform image + analysis and visual data extraction tasks. + +The combination of these diverse data sources is crucial for training a powerful +multimodal model that can handle a wide variety of different tasks and data +formats. + +### Data Preprocessing + +Here are the key data cleaning and filtering methods applied to the training +data: + +- CSAM Filtering: Rigorous CSAM (Child Sexual Abuse Material) filtering + was applied at multiple stages in the data preparation process to ensure + the exclusion of harmful and illegal content. +- Sensitive Data Filtering: As part of making Gemma pre-trained models + safe and reliable, automated techniques were used to filter out certain + personal information and other sensitive data from training sets. +- Additional methods: Filtering based on content quality and safety in + line with [our policies][safety-policies]. + +## Implementation Information + +Details about the model internals. + +### Hardware + +Gemma was trained using [Tensor Processing Unit (TPU)][tpu] hardware (TPUv4p, +TPUv5p and TPUv5e). Training vision-language models (VLMS) requires significant +computational power. TPUs, designed specifically for matrix operations common in +machine learning, offer several advantages in this domain: + +- Performance: TPUs are specifically designed to handle the massive + computations involved in training VLMs. They can speed up training + considerably compared to CPUs. +- Memory: TPUs often come with large amounts of high-bandwidth memory, + allowing for the handling of large models and batch sizes during training. + This can lead to better model quality. +- Scalability: TPU Pods (large clusters of TPUs) provide a scalable + solution for handling the growing complexity of large foundation models. + You can distribute training across multiple TPU devices for faster and more + efficient processing. +- Cost-effectiveness: In many scenarios, TPUs can provide a more + cost-effective solution for training large models compared to CPU-based + infrastructure, especially when considering the time and resources saved + due to faster training. +- These advantages are aligned with + [Google's commitments to operate sustainably][sustainability]. + +### Software + +Training was done using [JAX][jax] and [ML Pathways][ml-pathways]. + +JAX allows researchers to take advantage of the latest generation of hardware, +including TPUs, for faster and more efficient training of large models. ML +Pathways is Google's latest effort to build artificially intelligent systems +capable of generalizing across multiple tasks. This is specially suitable for +foundation models, including large language models like these ones. + +Together, JAX and ML Pathways are used as described in the +[paper about the Gemini family of models][gemini-2-paper]; *"the 'single +controller' programming model of Jax and Pathways allows a single Python +process to orchestrate the entire training run, dramatically simplifying the +development workflow."* + +## Evaluation + +Model evaluation metrics and results. + +### Benchmark Results + +These models were evaluated against a large collection of different datasets and +metrics to cover different aspects of text generation: + +#### Reasoning and factuality + +| Benchmark | Metric | Gemma 3 PT 1B | Gemma 3 PT 4B | Gemma 3 PT 12B | Gemma 3 PT 27B | +| ------------------------------ |----------------|:--------------:|:-------------:|:--------------:|:--------------:| +| [HellaSwag][hellaswag] | 10-shot | 62.3 | 77.2 | 84.2 | 85.6 | +| [BoolQ][boolq] | 0-shot | 63.2 | 72.3 | 78.8 | 82.4 | +| [PIQA][piqa] | 0-shot | 73.8 | 79.6 | 81.8 | 83.3 | +| [SocialIQA][socialiqa] | 0-shot | 48.9 | 51.9 | 53.4 | 54.9 | +| [TriviaQA][triviaqa] | 5-shot | 39.8 | 65.8 | 78.2 | 85.5 | +| [Natural Questions][naturalq] | 5-shot | 9.48 | 20.0 | 31.4 | 36.1 | +| [ARC-c][arc] | 25-shot | 38.4 | 56.2 | 68.9 | 70.6 | +| [ARC-e][arc] | 0-shot | 73.0 | 82.4 | 88.3 | 89.0 | +| [WinoGrande][winogrande] | 5-shot | 58.2 | 64.7 | 74.3 | 78.8 | +| [BIG-Bench Hard][bbh] | few-shot | 28.4 | 50.9 | 72.6 | 77.7 | +| [DROP][drop] | 1-shot | 42.4 | 60.1 | 72.2 | 77.2 | + +[hellaswag]: https://arxiv.org/abs/1905.07830 +[boolq]: https://arxiv.org/abs/1905.10044 +[piqa]: https://arxiv.org/abs/1911.11641 +[socialiqa]: https://arxiv.org/abs/1904.09728 +[triviaqa]: https://arxiv.org/abs/1705.03551 +[naturalq]: https://github.com/google-research-datasets/natural-questions +[arc]: https://arxiv.org/abs/1911.01547 +[winogrande]: https://arxiv.org/abs/1907.10641 +[bbh]: https://paperswithcode.com/dataset/bbh +[drop]: https://arxiv.org/abs/1903.00161 + +#### STEM and code + +| Benchmark | Metric | Gemma 3 PT 4B | Gemma 3 PT 12B | Gemma 3 PT 27B | +| ------------------------------ |----------------|:-------------:|:--------------:|:--------------:| +| [MMLU][mmlu] | 5-shot | 59.6 | 74.5 | 78.6 | +| [MMLU][mmlu] (Pro COT) | 5-shot | 29.2 | 45.3 | 52.2 | +| [AGIEval][agieval] | 3-5-shot | 42.1 | 57.4 | 66.2 | +| [MATH][math] | 4-shot | 24.2 | 43.3 | 50.0 | +| [GSM8K][gsm8k] | 8-shot | 38.4 | 71.0 | 82.6 | +| [GPQA][gpqa] | 5-shot | 15.0 | 25.4 | 24.3 | +| [MBPP][mbpp] | 3-shot | 46.0 | 60.4 | 65.6 | +| [HumanEval][humaneval] | 0-shot | 36.0 | 45.7 | 48.8 | + +[mmlu]: https://arxiv.org/abs/2009.03300 +[agieval]: https://arxiv.org/abs/2304.06364 +[math]: https://arxiv.org/abs/2103.03874 +[gsm8k]: https://arxiv.org/abs/2110.14168 +[gpqa]: https://arxiv.org/abs/2311.12022 +[mbpp]: https://arxiv.org/abs/2108.07732 +[humaneval]: https://arxiv.org/abs/2107.03374 + +#### Multilingual + +| Benchmark | Gemma 3 PT 1B | Gemma 3 PT 4B | Gemma 3 PT 12B | Gemma 3 PT 27B | +| ------------------------------------ |:-------------:|:-------------:|:--------------:|:--------------:| +| [MGSM][mgsm] | 2.04 | 34.7 | 64.3 | 74.3 | +| [Global-MMLU-Lite][global-mmlu-lite] | 24.9 | 57.0 | 69.4 | 75.7 | +| [WMT24++][wmt24pp] (ChrF) | 36.7 | 48.4 | 53.9 | 55.7 | +| [FloRes][flores] | 29.5 | 39.2 | 46.0 | 48.8 | +| [XQuAD][xquad] (all) | 43.9 | 68.0 | 74.5 | 76.8 | +| [ECLeKTic][eclektic] | 4.69 | 11.0 | 17.2 | 24.4 | +| [IndicGenBench][indicgenbench] | 41.4 | 57.2 | 61.7 | 63.4 | + +[mgsm]: https://arxiv.org/abs/2210.03057 +[flores]: https://arxiv.org/abs/2106.03193 +[xquad]: https://arxiv.org/abs/1910.11856v3 +[global-mmlu-lite]: https://huggingface.co/datasets/CohereForAI/Global-MMLU-Lite +[wmt24pp]: https://arxiv.org/abs/2502.12404v1 +[eclektic]: https://arxiv.org/abs/2502.21228 +[indicgenbench]: https://arxiv.org/abs/2404.16816 + +#### Multimodal + +| Benchmark | Gemma 3 PT 4B | Gemma 3 PT 12B | Gemma 3 PT 27B | +| ------------------------------ |:-------------:|:--------------:|:--------------:| +| [COCOcap][coco-cap] | 102 | 111 | 116 | +| [DocVQA][docvqa] (val) | 72.8 | 82.3 | 85.6 | +| [InfoVQA][info-vqa] (val) | 44.1 | 54.8 | 59.4 | +| [MMMU][mmmu] (pt) | 39.2 | 50.3 | 56.1 | +| [TextVQA][textvqa] (val) | 58.9 | 66.5 | 68.6 | +| [RealWorldQA][realworldqa] | 45.5 | 52.2 | 53.9 | +| [ReMI][remi] | 27.3 | 38.5 | 44.8 | +| [AI2D][ai2d] | 63.2 | 75.2 | 79.0 | +| [ChartQA][chartqa] | 63.6 | 74.7 | 76.3 | +| [VQAv2][vqav2] | 63.9 | 71.2 | 72.9 | +| [BLINK][blinkvqa] | 38.0 | 35.9 | 39.6 | +| [OKVQA][okvqa] | 51.0 | 58.7 | 60.2 | +| [TallyQA][tallyqa] | 42.5 | 51.8 | 54.3 | +| [SpatialSense VQA][ss-vqa] | 50.9 | 60.0 | 59.4 | +| [CountBenchQA][countbenchqa] | 26.1 | 17.8 | 68.0 | + +[coco-cap]: https://cocodataset.org/#home +[docvqa]: https://www.docvqa.org/ +[info-vqa]: https://arxiv.org/abs/2104.12756 +[mmmu]: https://arxiv.org/abs/2311.16502 +[textvqa]: https://textvqa.org/ +[realworldqa]: https://paperswithcode.com/dataset/realworldqa +[remi]: https://arxiv.org/html/2406.09175v1 +[ai2d]: https://allenai.org/data/diagrams +[chartqa]: https://arxiv.org/abs/2203.10244 +[vqav2]: https://visualqa.org/index.html +[blinkvqa]: https://arxiv.org/abs/2404.12390 +[okvqa]: https://okvqa.allenai.org/ +[tallyqa]: https://arxiv.org/abs/1810.12440 +[ss-vqa]: https://arxiv.org/abs/1908.02660 +[countbenchqa]: https://github.com/google-research/big_vision/blob/main/big_vision/datasets/countbenchqa/ + +## Ethics and Safety + +Ethics and safety evaluation approach and results. + +### Evaluation Approach + +Our evaluation methods include structured evaluations and internal red-teaming +testing of relevant content policies. Red-teaming was conducted by a number of +different teams, each with different goals and human evaluation metrics. These +models were evaluated against a number of different categories relevant to +ethics and safety, including: + +- **Child Safety**: Evaluation of text-to-text and image to text prompts + covering child safety policies, including child sexual abuse and + exploitation. +- **Content Safety:** Evaluation of text-to-text and image to text prompts + covering safety policies including, harassment, violence and gore, and hate + speech. +- **Representational Harms**: Evaluation of text-to-text and image to text + prompts covering safety policies including bias, stereotyping, and harmful + associations or inaccuracies. + +In addition to development level evaluations, we conduct "assurance +evaluations" which are our 'arms-length' internal evaluations for responsibility +governance decision making. They are conducted separately from the model +development team, to inform decision making about release. High level findings +are fed back to the model team, but prompt sets are held-out to prevent +overfitting and preserve the results' ability to inform decision making. +Assurance evaluation results are reported to our Responsibility & Safety Council +as part of release review. + +### Evaluation Results + +For all areas of safety testing, we saw major improvements in the categories of +child safety, content safety, and representational harms relative to previous +Gemma models. All testing was conducted without safety filters to evaluate the +model capabilities and behaviors. For both text-to-text and image-to-text, and +across all model sizes, the model produced minimal policy violations, and showed +significant improvements over previous Gemma models' performance with respect +to ungrounded inferences. A limitation of our evaluations was they included only +English language prompts. + +## Usage and Limitations + +These models have certain limitations that users should be aware of. + +### Intended Usage + +Open vision-language models (VLMs) models have a wide range of applications +across various industries and domains. The following list of potential uses is +not comprehensive. The purpose of this list is to provide contextual information +about the possible use-cases that the model creators considered as part of model +training and development. + +- Content Creation and Communication + - Text Generation: These models can be used to generate creative text + formats such as poems, scripts, code, marketing copy, and email drafts. + - Chatbots and Conversational AI: Power conversational interfaces + for customer service, virtual assistants, or interactive applications. + - Text Summarization: Generate concise summaries of a text corpus, + research papers, or reports. + - Image Data Extraction: These models can be used to extract, + interpret, and summarize visual data for text communications. +- Research and Education + - Natural Language Processing (NLP) and VLM Research: These + models can serve as a foundation for researchers to experiment with VLM + and NLP techniques, develop algorithms, and contribute to the + advancement of the field. + - Language Learning Tools: Support interactive language learning + experiences, aiding in grammar correction or providing writing practice. + - Knowledge Exploration: Assist researchers in exploring large + bodies of text by generating summaries or answering questions about + specific topics. + +### Limitations + +- Training Data + - The quality and diversity of the training data significantly + influence the model's capabilities. Biases or gaps in the training data + can lead to limitations in the model's responses. + - The scope of the training dataset determines the subject areas + the model can handle effectively. +- Context and Task Complexity + - Models are better at tasks that can be framed with clear + prompts and instructions. Open-ended or highly complex tasks might be + challenging. + - A model's performance can be influenced by the amount of context + provided (longer context generally leads to better outputs, up to a + certain point). +- Language Ambiguity and Nuance + - Natural language is inherently complex. Models might struggle + to grasp subtle nuances, sarcasm, or figurative language. +- Factual Accuracy + - Models generate responses based on information they learned + from their training datasets, but they are not knowledge bases. They + may generate incorrect or outdated factual statements. +- Common Sense + - Models rely on statistical patterns in language. They might + lack the ability to apply common sense reasoning in certain situations. + +### Ethical Considerations and Risks + +The development of vision-language models (VLMs) raises several ethical +concerns. In creating an open model, we have carefully considered the following: + +- Bias and Fairness + - VLMs trained on large-scale, real-world text and image data can + reflect socio-cultural biases embedded in the training material. These + models underwent careful scrutiny, input data pre-processing described + and posterior evaluations reported in this card. +- Misinformation and Misuse + - VLMs can be misused to generate text that is false, misleading, + or harmful. + - Guidelines are provided for responsible use with the model, see the + [Responsible Generative AI Toolkit][rai-toolkit]. +- Transparency and Accountability: + - This model card summarizes details on the models' architecture, + capabilities, limitations, and evaluation processes. + - A responsibly developed open model offers the opportunity to + share innovation by making VLM technology accessible to developers and + researchers across the AI ecosystem. + +Risks identified and mitigations: + +- **Perpetuation of biases**: It's encouraged to perform continuous + monitoring (using evaluation metrics, human review) and the exploration of + de-biasing techniques during model training, fine-tuning, and other use + cases. +- **Generation of harmful content**: Mechanisms and guidelines for content + safety are essential. Developers are encouraged to exercise caution and + implement appropriate content safety safeguards based on their specific + product policies and application use cases. +- **Misuse for malicious purposes**: Technical limitations and developer + and end-user education can help mitigate against malicious applications of + VLMs. Educational resources and reporting mechanisms for users to flag + misuse are provided. Prohibited uses of Gemma models are outlined in the + [Gemma Prohibited Use Policy][prohibited-use]. +- **Privacy violations**: Models were trained on data filtered for removal + of certain personal information and other sensitive data. Developers are + encouraged to adhere to privacy regulations with privacy-preserving + techniques. + +### Benefits + +At the time of release, this family of models provides high-performance open +vision-language model implementations designed from the ground up for +responsible AI development compared to similarly sized models. + +Using the benchmark evaluation metrics described in this document, these models +have shown to provide superior performance to other, comparably-sized open model +alternatives. + +[g3-tech-report]: https://goo.gle/Gemma3Report +[rai-toolkit]: https://ai.google.dev/responsible +[kaggle-gemma]: https://www.kaggle.com/models/google/gemma-3 +[vertex-mg-gemma3]: https://console.cloud.google.com/vertex-ai/publishers/google/model-garden/gemma3 +[terms]: https://ai.google.dev/gemma/terms +[safety-policies]: https://ai.google/static/documents/ai-responsibility-update-published-february-2025.pdf +[prohibited-use]: https://ai.google.dev/gemma/prohibited_use_policy +[tpu]: https://cloud.google.com/tpu/docs/intro-to-tpu +[sustainability]: https://sustainability.google/operating-sustainably/ +[jax]: https://github.com/jax-ml/jax +[ml-pathways]: https://blog.google/technology/ai/introducing-pathways-next-generation-ai-architecture/ +[sustainability]: https://sustainability.google/operating-sustainably/ +[gemini-2-paper]: https://arxiv.org/abs/2312.11805 \ No newline at end of file diff --git a/VRGDG_Musubi-tuner/models/gemma-3-12b-it/added_tokens.json b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/added_tokens.json new file mode 100644 index 0000000000000000000000000000000000000000..e17bde03d42feda32d1abfca6d3b598b9a020df7 --- /dev/null +++ b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/added_tokens.json @@ -0,0 +1,3 @@ +{ + "": 262144 +} diff --git a/VRGDG_Musubi-tuner/models/gemma-3-12b-it/chat_template.json b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/chat_template.json new file mode 100644 index 0000000000000000000000000000000000000000..719b0cd0d7a373a400b0c119ee0e051f41ea88d9 --- /dev/null +++ b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/chat_template.json @@ -0,0 +1,3 @@ +{ + "chat_template": "{{ bos_token }}\n{%- if messages[0]['role'] == 'system' -%}\n {%- if messages[0]['content'] is string -%}\n {%- set first_user_prefix = messages[0]['content'] + '\n\n' -%}\n {%- else -%}\n {%- set first_user_prefix = messages[0]['content'][0]['text'] + '\n\n' -%}\n {%- endif -%}\n {%- set loop_messages = messages[1:] -%}\n{%- else -%}\n {%- set first_user_prefix = \"\" -%}\n {%- set loop_messages = messages -%}\n{%- endif -%}\n{%- for message in loop_messages -%}\n {%- if (message['role'] == 'user') != (loop.index0 % 2 == 0) -%}\n {{ raise_exception(\"Conversation roles must alternate user/assistant/user/assistant/...\") }}\n {%- endif -%}\n {%- if (message['role'] == 'assistant') -%}\n {%- set role = \"model\" -%}\n {%- else -%}\n {%- set role = message['role'] -%}\n {%- endif -%}\n {{ '' + role + '\n' + (first_user_prefix if loop.first else \"\") }}\n {%- if message['content'] is string -%}\n {{ message['content'] | trim }}\n {%- elif message['content'] is iterable -%}\n {%- for item in message['content'] -%}\n {%- if item['type'] == 'image' -%}\n {{ '' }}\n {%- elif item['type'] == 'text' -%}\n {{ item['text'] | trim }}\n {%- endif -%}\n {%- endfor -%}\n {%- else -%}\n {{ raise_exception(\"Invalid content type\") }}\n {%- endif -%}\n {{ '\n' }}\n{%- endfor -%}\n{%- if add_generation_prompt -%}\n {{'model\n'}}\n{%- endif -%}\n" +} diff --git a/VRGDG_Musubi-tuner/models/gemma-3-12b-it/config.json b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/config.json new file mode 100644 index 0000000000000000000000000000000000000000..0fbe1ff508fb71af7056eed3397faaa0349a8f09 --- /dev/null +++ b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/config.json @@ -0,0 +1,40 @@ +{ + "architectures": [ + "Gemma3ForConditionalGeneration" + ], + "boi_token_index": 255999, + "eoi_token_index": 256000, + "eos_token_id": [ + 1, + 106 + ], + "image_token_index": 262144, + "initializer_range": 0.02, + "mm_tokens_per_image": 256, + "model_type": "gemma3", + "text_config": { + "hidden_size": 3840, + "intermediate_size": 15360, + "model_type": "gemma3_text", + "num_attention_heads": 16, + "num_hidden_layers": 48, + "num_key_value_heads": 8, + "rope_scaling": { + "factor": 8.0, + "rope_type": "linear" + }, + "sliding_window": 1024 + }, + "torch_dtype": "bfloat16", + "transformers_version": "4.50.0.dev0", + "vision_config": { + "hidden_size": 1152, + "image_size": 896, + "intermediate_size": 4304, + "model_type": "siglip_vision_model", + "num_attention_heads": 16, + "num_hidden_layers": 27, + "patch_size": 14, + "vision_use_head": false + } +} diff --git a/VRGDG_Musubi-tuner/models/gemma-3-12b-it/generation_config.json b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/generation_config.json new file mode 100644 index 0000000000000000000000000000000000000000..37a4c871d263a349f50e4a313db3e72164950702 --- /dev/null +++ b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/generation_config.json @@ -0,0 +1,13 @@ +{ + "bos_token_id": 2, + "cache_implementation": "hybrid", + "do_sample": true, + "eos_token_id": [ + 1, + 106 + ], + "pad_token_id": 0, + "top_k": 64, + "top_p": 0.95, + "transformers_version": "4.50.0.dev0" +} diff --git a/VRGDG_Musubi-tuner/models/gemma-3-12b-it/model-00001-of-00005.safetensors b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/model-00001-of-00005.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..b31bb2df2dc13fd8028e51899bdb1e7a4fb6d167 --- /dev/null +++ b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/model-00001-of-00005.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4847447e92599833e8dbaa3067cd201c3bb5c052efa91f11ba891e43234f7832 +size 4979902192 diff --git a/VRGDG_Musubi-tuner/models/gemma-3-12b-it/model-00002-of-00005.safetensors b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/model-00002-of-00005.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..5eb217601f2c82b83e3e7ae754d183429d9dde4e --- /dev/null +++ b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/model-00002-of-00005.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:891bd54eed03cba9ee1e705533a02a8217fcc29f356e4a1f53e5fd0d178883ad +size 4931296592 diff --git a/VRGDG_Musubi-tuner/models/gemma-3-12b-it/model-00003-of-00005.safetensors b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/model-00003-of-00005.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..425bcf00b3eb7c7ef42496d1500591e4f8068b72 --- /dev/null +++ b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/model-00003-of-00005.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7cee411d9d57324e50ce064a192cc5a858276d508611b12fc599e0c9767112e0 +size 4931296656 diff --git a/VRGDG_Musubi-tuner/models/gemma-3-12b-it/model-00004-of-00005.safetensors b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/model-00004-of-00005.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..71b7dba9bf563fdb2f5cc1a518483adfdc91d1a3 --- /dev/null +++ b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/model-00004-of-00005.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8bc75a29a730c9e743cad013feda3b0991a913fafe787c58a1c6e20afad97723 +size 4931296656 diff --git a/VRGDG_Musubi-tuner/models/gemma-3-12b-it/model-00005-of-00005.safetensors b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/model-00005-of-00005.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..2e7be9e5bfa8222c2bfe34159586d2b1f35fd505 --- /dev/null +++ b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/model-00005-of-00005.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ed14bd4908c98fed9f61e8cd410167e0846de9abd78e0452ab092072e5d9252d +size 4601000928 diff --git a/VRGDG_Musubi-tuner/models/gemma-3-12b-it/model.safetensors.index.json b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/model.safetensors.index.json new file mode 100644 index 0000000000000000000000000000000000000000..c5eb054c21efb5496f4623aeb619a750c9ed9357 --- /dev/null +++ b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/model.safetensors.index.json @@ -0,0 +1,1072 @@ +{ + "metadata": { + "total_size": 24374650080 + }, + "weight_map": { + "language_model.model.embed_tokens.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.0.input_layernorm.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.0.mlp.down_proj.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.0.mlp.gate_proj.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.0.mlp.up_proj.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.0.post_attention_layernorm.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.0.post_feedforward_layernorm.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.0.pre_feedforward_layernorm.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.0.self_attn.k_norm.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.0.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.0.self_attn.o_proj.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.0.self_attn.q_norm.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.0.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.0.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.1.input_layernorm.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.1.mlp.down_proj.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.1.mlp.gate_proj.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.1.mlp.up_proj.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.1.post_attention_layernorm.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.1.post_feedforward_layernorm.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.1.pre_feedforward_layernorm.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.1.self_attn.k_norm.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.1.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.1.self_attn.o_proj.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.1.self_attn.q_norm.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.1.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.1.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.10.input_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.10.mlp.down_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.10.mlp.gate_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.10.mlp.up_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.10.post_attention_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.10.post_feedforward_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.10.pre_feedforward_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.10.self_attn.k_norm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.10.self_attn.k_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.10.self_attn.o_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.10.self_attn.q_norm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.10.self_attn.q_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.10.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.11.input_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.11.mlp.down_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.11.mlp.gate_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.11.mlp.up_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.11.post_attention_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.11.post_feedforward_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.11.pre_feedforward_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.11.self_attn.k_norm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.11.self_attn.k_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.11.self_attn.o_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.11.self_attn.q_norm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.11.self_attn.q_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.11.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.12.input_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.12.mlp.down_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.12.mlp.gate_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.12.mlp.up_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.12.post_attention_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.12.post_feedforward_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.12.pre_feedforward_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.12.self_attn.k_norm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.12.self_attn.k_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.12.self_attn.o_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.12.self_attn.q_norm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.12.self_attn.q_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.12.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.13.input_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.13.mlp.down_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.13.mlp.gate_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.13.mlp.up_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.13.post_attention_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.13.post_feedforward_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.13.pre_feedforward_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.13.self_attn.k_norm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.13.self_attn.k_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.13.self_attn.o_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.13.self_attn.q_norm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.13.self_attn.q_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.13.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.14.input_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.14.mlp.down_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.14.mlp.gate_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.14.mlp.up_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.14.post_attention_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.14.post_feedforward_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.14.pre_feedforward_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.14.self_attn.k_norm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.14.self_attn.k_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.14.self_attn.o_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.14.self_attn.q_norm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.14.self_attn.q_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.14.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.15.input_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.15.mlp.down_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.15.mlp.gate_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.15.mlp.up_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.15.post_attention_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.15.post_feedforward_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.15.pre_feedforward_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.15.self_attn.k_norm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.15.self_attn.k_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.15.self_attn.o_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.15.self_attn.q_norm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.15.self_attn.q_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.15.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.16.input_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.16.mlp.down_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.16.mlp.gate_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.16.mlp.up_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.16.post_attention_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.16.post_feedforward_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.16.pre_feedforward_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.16.self_attn.k_norm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.16.self_attn.k_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.16.self_attn.o_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.16.self_attn.q_norm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.16.self_attn.q_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.16.self_attn.v_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.17.input_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.17.mlp.down_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.17.mlp.gate_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.17.mlp.up_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.17.post_attention_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.17.post_feedforward_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.17.pre_feedforward_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.17.self_attn.k_norm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.17.self_attn.k_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.17.self_attn.o_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.17.self_attn.q_norm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.17.self_attn.q_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.17.self_attn.v_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.18.input_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.18.mlp.down_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.18.mlp.gate_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.18.mlp.up_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.18.post_attention_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.18.post_feedforward_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.18.pre_feedforward_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.18.self_attn.k_norm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.18.self_attn.k_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.18.self_attn.o_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.18.self_attn.q_norm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.18.self_attn.q_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.18.self_attn.v_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.19.input_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.19.mlp.down_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.19.mlp.gate_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.19.mlp.up_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.19.post_attention_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.19.post_feedforward_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.19.pre_feedforward_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.19.self_attn.k_norm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.19.self_attn.k_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.19.self_attn.o_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.19.self_attn.q_norm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.19.self_attn.q_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.19.self_attn.v_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.2.input_layernorm.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.2.mlp.down_proj.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.2.mlp.gate_proj.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.2.mlp.up_proj.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.2.post_attention_layernorm.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.2.post_feedforward_layernorm.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.2.pre_feedforward_layernorm.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.2.self_attn.k_norm.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.2.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.2.self_attn.o_proj.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.2.self_attn.q_norm.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.2.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.2.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.20.input_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.20.mlp.down_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.20.mlp.gate_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.20.mlp.up_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.20.post_attention_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.20.post_feedforward_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.20.pre_feedforward_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.20.self_attn.k_norm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.20.self_attn.k_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.20.self_attn.o_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.20.self_attn.q_norm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.20.self_attn.q_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.20.self_attn.v_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.21.input_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.21.mlp.down_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.21.mlp.gate_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.21.mlp.up_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.21.post_attention_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.21.post_feedforward_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.21.pre_feedforward_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.21.self_attn.k_norm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.21.self_attn.k_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.21.self_attn.o_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.21.self_attn.q_norm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.21.self_attn.q_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.21.self_attn.v_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.22.input_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.22.mlp.down_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.22.mlp.gate_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.22.mlp.up_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.22.post_attention_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.22.post_feedforward_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.22.pre_feedforward_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.22.self_attn.k_norm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.22.self_attn.k_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.22.self_attn.o_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.22.self_attn.q_norm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.22.self_attn.q_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.22.self_attn.v_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.23.input_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.23.mlp.down_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.23.mlp.gate_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.23.mlp.up_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.23.post_attention_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.23.post_feedforward_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.23.pre_feedforward_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.23.self_attn.k_norm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.23.self_attn.k_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.23.self_attn.o_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.23.self_attn.q_norm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.23.self_attn.q_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.23.self_attn.v_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.24.input_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.24.mlp.down_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.24.mlp.gate_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.24.mlp.up_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.24.post_attention_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.24.post_feedforward_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.24.pre_feedforward_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.24.self_attn.k_norm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.24.self_attn.k_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.24.self_attn.o_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.24.self_attn.q_norm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.24.self_attn.q_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.24.self_attn.v_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.25.input_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.25.mlp.down_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.25.mlp.gate_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.25.mlp.up_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.25.post_attention_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.25.post_feedforward_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.25.pre_feedforward_layernorm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.25.self_attn.k_norm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.25.self_attn.k_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.25.self_attn.o_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.25.self_attn.q_norm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.25.self_attn.q_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.25.self_attn.v_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.26.input_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.26.mlp.down_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.26.mlp.gate_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.26.mlp.up_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.26.post_attention_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.26.post_feedforward_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.26.pre_feedforward_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.26.self_attn.k_norm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.26.self_attn.k_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.26.self_attn.o_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.26.self_attn.q_norm.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.26.self_attn.q_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.26.self_attn.v_proj.weight": "model-00003-of-00005.safetensors", + "language_model.model.layers.27.input_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.27.mlp.down_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.27.mlp.gate_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.27.mlp.up_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.27.post_attention_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.27.post_feedforward_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.27.pre_feedforward_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.27.self_attn.k_norm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.27.self_attn.k_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.27.self_attn.o_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.27.self_attn.q_norm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.27.self_attn.q_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.27.self_attn.v_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.28.input_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.28.mlp.down_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.28.mlp.gate_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.28.mlp.up_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.28.post_attention_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.28.post_feedforward_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.28.pre_feedforward_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.28.self_attn.k_norm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.28.self_attn.k_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.28.self_attn.o_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.28.self_attn.q_norm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.28.self_attn.q_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.28.self_attn.v_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.29.input_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.29.mlp.down_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.29.mlp.gate_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.29.mlp.up_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.29.post_attention_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.29.post_feedforward_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.29.pre_feedforward_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.29.self_attn.k_norm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.29.self_attn.k_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.29.self_attn.o_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.29.self_attn.q_norm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.29.self_attn.q_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.29.self_attn.v_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.3.input_layernorm.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.3.mlp.down_proj.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.3.mlp.gate_proj.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.3.mlp.up_proj.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.3.post_attention_layernorm.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.3.post_feedforward_layernorm.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.3.pre_feedforward_layernorm.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.3.self_attn.k_norm.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.3.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.3.self_attn.o_proj.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.3.self_attn.q_norm.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.3.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.3.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.30.input_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.30.mlp.down_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.30.mlp.gate_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.30.mlp.up_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.30.post_attention_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.30.post_feedforward_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.30.pre_feedforward_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.30.self_attn.k_norm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.30.self_attn.k_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.30.self_attn.o_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.30.self_attn.q_norm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.30.self_attn.q_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.30.self_attn.v_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.31.input_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.31.mlp.down_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.31.mlp.gate_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.31.mlp.up_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.31.post_attention_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.31.post_feedforward_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.31.pre_feedforward_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.31.self_attn.k_norm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.31.self_attn.k_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.31.self_attn.o_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.31.self_attn.q_norm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.31.self_attn.q_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.31.self_attn.v_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.32.input_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.32.mlp.down_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.32.mlp.gate_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.32.mlp.up_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.32.post_attention_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.32.post_feedforward_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.32.pre_feedforward_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.32.self_attn.k_norm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.32.self_attn.k_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.32.self_attn.o_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.32.self_attn.q_norm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.32.self_attn.q_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.32.self_attn.v_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.33.input_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.33.mlp.down_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.33.mlp.gate_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.33.mlp.up_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.33.post_attention_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.33.post_feedforward_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.33.pre_feedforward_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.33.self_attn.k_norm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.33.self_attn.k_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.33.self_attn.o_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.33.self_attn.q_norm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.33.self_attn.q_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.33.self_attn.v_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.34.input_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.34.mlp.down_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.34.mlp.gate_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.34.mlp.up_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.34.post_attention_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.34.post_feedforward_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.34.pre_feedforward_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.34.self_attn.k_norm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.34.self_attn.k_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.34.self_attn.o_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.34.self_attn.q_norm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.34.self_attn.q_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.34.self_attn.v_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.35.input_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.35.mlp.down_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.35.mlp.gate_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.35.mlp.up_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.35.post_attention_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.35.post_feedforward_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.35.pre_feedforward_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.35.self_attn.k_norm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.35.self_attn.k_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.35.self_attn.o_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.35.self_attn.q_norm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.35.self_attn.q_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.35.self_attn.v_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.36.input_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.36.mlp.down_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.36.mlp.gate_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.36.mlp.up_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.36.post_attention_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.36.post_feedforward_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.36.pre_feedforward_layernorm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.36.self_attn.k_norm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.36.self_attn.k_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.36.self_attn.o_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.36.self_attn.q_norm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.36.self_attn.q_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.36.self_attn.v_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.37.input_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.37.mlp.down_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.37.mlp.gate_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.37.mlp.up_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.37.post_attention_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.37.post_feedforward_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.37.pre_feedforward_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.37.self_attn.k_norm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.37.self_attn.k_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.37.self_attn.o_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.37.self_attn.q_norm.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.37.self_attn.q_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.37.self_attn.v_proj.weight": "model-00004-of-00005.safetensors", + "language_model.model.layers.38.input_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.38.mlp.down_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.38.mlp.gate_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.38.mlp.up_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.38.post_attention_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.38.post_feedforward_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.38.pre_feedforward_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.38.self_attn.k_norm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.38.self_attn.k_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.38.self_attn.o_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.38.self_attn.q_norm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.38.self_attn.q_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.38.self_attn.v_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.39.input_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.39.mlp.down_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.39.mlp.gate_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.39.mlp.up_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.39.post_attention_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.39.post_feedforward_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.39.pre_feedforward_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.39.self_attn.k_norm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.39.self_attn.k_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.39.self_attn.o_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.39.self_attn.q_norm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.39.self_attn.q_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.39.self_attn.v_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.4.input_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.4.mlp.down_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.4.mlp.gate_proj.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.4.mlp.up_proj.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.4.post_attention_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.4.post_feedforward_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.4.pre_feedforward_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.4.self_attn.k_norm.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.4.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.4.self_attn.o_proj.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.4.self_attn.q_norm.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.4.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.4.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", + "language_model.model.layers.40.input_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.40.mlp.down_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.40.mlp.gate_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.40.mlp.up_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.40.post_attention_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.40.post_feedforward_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.40.pre_feedforward_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.40.self_attn.k_norm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.40.self_attn.k_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.40.self_attn.o_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.40.self_attn.q_norm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.40.self_attn.q_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.40.self_attn.v_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.41.input_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.41.mlp.down_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.41.mlp.gate_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.41.mlp.up_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.41.post_attention_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.41.post_feedforward_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.41.pre_feedforward_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.41.self_attn.k_norm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.41.self_attn.k_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.41.self_attn.o_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.41.self_attn.q_norm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.41.self_attn.q_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.41.self_attn.v_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.42.input_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.42.mlp.down_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.42.mlp.gate_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.42.mlp.up_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.42.post_attention_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.42.post_feedforward_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.42.pre_feedforward_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.42.self_attn.k_norm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.42.self_attn.k_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.42.self_attn.o_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.42.self_attn.q_norm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.42.self_attn.q_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.42.self_attn.v_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.43.input_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.43.mlp.down_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.43.mlp.gate_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.43.mlp.up_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.43.post_attention_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.43.post_feedforward_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.43.pre_feedforward_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.43.self_attn.k_norm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.43.self_attn.k_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.43.self_attn.o_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.43.self_attn.q_norm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.43.self_attn.q_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.43.self_attn.v_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.44.input_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.44.mlp.down_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.44.mlp.gate_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.44.mlp.up_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.44.post_attention_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.44.post_feedforward_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.44.pre_feedforward_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.44.self_attn.k_norm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.44.self_attn.k_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.44.self_attn.o_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.44.self_attn.q_norm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.44.self_attn.q_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.44.self_attn.v_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.45.input_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.45.mlp.down_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.45.mlp.gate_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.45.mlp.up_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.45.post_attention_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.45.post_feedforward_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.45.pre_feedforward_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.45.self_attn.k_norm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.45.self_attn.k_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.45.self_attn.o_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.45.self_attn.q_norm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.45.self_attn.q_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.45.self_attn.v_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.46.input_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.46.mlp.down_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.46.mlp.gate_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.46.mlp.up_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.46.post_attention_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.46.post_feedforward_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.46.pre_feedforward_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.46.self_attn.k_norm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.46.self_attn.k_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.46.self_attn.o_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.46.self_attn.q_norm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.46.self_attn.q_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.46.self_attn.v_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.47.input_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.47.mlp.down_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.47.mlp.gate_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.47.mlp.up_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.47.post_attention_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.47.post_feedforward_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.47.pre_feedforward_layernorm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.47.self_attn.k_norm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.47.self_attn.k_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.47.self_attn.o_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.47.self_attn.q_norm.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.47.self_attn.q_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.47.self_attn.v_proj.weight": "model-00005-of-00005.safetensors", + "language_model.model.layers.5.input_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.5.mlp.down_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.5.mlp.gate_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.5.mlp.up_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.5.post_attention_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.5.post_feedforward_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.5.pre_feedforward_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.5.self_attn.k_norm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.5.self_attn.k_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.5.self_attn.o_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.5.self_attn.q_norm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.5.self_attn.q_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.5.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.6.input_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.6.mlp.down_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.6.mlp.gate_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.6.mlp.up_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.6.post_attention_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.6.post_feedforward_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.6.pre_feedforward_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.6.self_attn.k_norm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.6.self_attn.k_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.6.self_attn.o_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.6.self_attn.q_norm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.6.self_attn.q_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.6.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.7.input_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.7.mlp.down_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.7.mlp.gate_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.7.mlp.up_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.7.post_attention_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.7.post_feedforward_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.7.pre_feedforward_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.7.self_attn.k_norm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.7.self_attn.k_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.7.self_attn.o_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.7.self_attn.q_norm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.7.self_attn.q_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.7.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.8.input_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.8.mlp.down_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.8.mlp.gate_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.8.mlp.up_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.8.post_attention_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.8.post_feedforward_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.8.pre_feedforward_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.8.self_attn.k_norm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.8.self_attn.k_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.8.self_attn.o_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.8.self_attn.q_norm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.8.self_attn.q_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.8.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.9.input_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.9.mlp.down_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.9.mlp.gate_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.9.mlp.up_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.9.post_attention_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.9.post_feedforward_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.9.pre_feedforward_layernorm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.9.self_attn.k_norm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.9.self_attn.k_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.9.self_attn.o_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.9.self_attn.q_norm.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.9.self_attn.q_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.layers.9.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", + "language_model.model.norm.weight": "model-00005-of-00005.safetensors", + "multi_modal_projector.mm_input_projection_weight": "model-00001-of-00005.safetensors", + "multi_modal_projector.mm_soft_emb_norm.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.embeddings.patch_embedding.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.embeddings.patch_embedding.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.embeddings.position_embedding.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.0.layer_norm1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.0.layer_norm1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.0.layer_norm2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.0.layer_norm2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.0.mlp.fc1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.0.mlp.fc1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.0.mlp.fc2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.0.mlp.fc2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.0.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.0.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.0.self_attn.out_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.0.self_attn.out_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.0.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.0.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.0.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.0.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.1.layer_norm1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.1.layer_norm1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.1.layer_norm2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.1.layer_norm2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.1.mlp.fc1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.1.mlp.fc1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.1.mlp.fc2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.1.mlp.fc2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.1.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.1.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.1.self_attn.out_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.1.self_attn.out_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.1.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.1.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.1.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.1.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.10.layer_norm1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.10.layer_norm1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.10.layer_norm2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.10.layer_norm2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.10.mlp.fc1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.10.mlp.fc1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.10.mlp.fc2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.10.mlp.fc2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.10.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.10.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.10.self_attn.out_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.10.self_attn.out_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.10.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.10.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.10.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.10.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.11.layer_norm1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.11.layer_norm1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.11.layer_norm2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.11.layer_norm2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.11.mlp.fc1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.11.mlp.fc1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.11.mlp.fc2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.11.mlp.fc2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.11.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.11.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.11.self_attn.out_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.11.self_attn.out_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.11.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.11.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.11.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.11.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.12.layer_norm1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.12.layer_norm1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.12.layer_norm2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.12.layer_norm2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.12.mlp.fc1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.12.mlp.fc1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.12.mlp.fc2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.12.mlp.fc2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.12.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.12.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.12.self_attn.out_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.12.self_attn.out_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.12.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.12.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.12.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.12.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.13.layer_norm1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.13.layer_norm1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.13.layer_norm2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.13.layer_norm2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.13.mlp.fc1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.13.mlp.fc1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.13.mlp.fc2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.13.mlp.fc2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.13.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.13.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.13.self_attn.out_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.13.self_attn.out_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.13.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.13.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.13.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.13.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.14.layer_norm1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.14.layer_norm1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.14.layer_norm2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.14.layer_norm2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.14.mlp.fc1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.14.mlp.fc1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.14.mlp.fc2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.14.mlp.fc2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.14.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.14.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.14.self_attn.out_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.14.self_attn.out_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.14.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.14.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.14.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.14.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.15.layer_norm1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.15.layer_norm1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.15.layer_norm2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.15.layer_norm2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.15.mlp.fc1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.15.mlp.fc1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.15.mlp.fc2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.15.mlp.fc2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.15.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.15.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.15.self_attn.out_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.15.self_attn.out_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.15.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.15.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.15.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.15.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.16.layer_norm1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.16.layer_norm1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.16.layer_norm2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.16.layer_norm2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.16.mlp.fc1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.16.mlp.fc1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.16.mlp.fc2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.16.mlp.fc2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.16.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.16.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.16.self_attn.out_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.16.self_attn.out_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.16.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.16.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.16.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.16.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.17.layer_norm1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.17.layer_norm1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.17.layer_norm2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.17.layer_norm2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.17.mlp.fc1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.17.mlp.fc1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.17.mlp.fc2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.17.mlp.fc2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.17.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.17.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.17.self_attn.out_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.17.self_attn.out_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.17.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.17.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.17.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.17.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.18.layer_norm1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.18.layer_norm1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.18.layer_norm2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.18.layer_norm2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.18.mlp.fc1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.18.mlp.fc1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.18.mlp.fc2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.18.mlp.fc2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.18.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.18.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.18.self_attn.out_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.18.self_attn.out_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.18.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.18.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.18.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.18.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.19.layer_norm1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.19.layer_norm1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.19.layer_norm2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.19.layer_norm2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.19.mlp.fc1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.19.mlp.fc1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.19.mlp.fc2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.19.mlp.fc2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.19.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.19.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.19.self_attn.out_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.19.self_attn.out_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.19.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.19.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.19.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.19.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.2.layer_norm1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.2.layer_norm1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.2.layer_norm2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.2.layer_norm2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.2.mlp.fc1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.2.mlp.fc1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.2.mlp.fc2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.2.mlp.fc2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.2.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.2.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.2.self_attn.out_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.2.self_attn.out_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.2.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.2.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.2.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.2.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.20.layer_norm1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.20.layer_norm1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.20.layer_norm2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.20.layer_norm2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.20.mlp.fc1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.20.mlp.fc1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.20.mlp.fc2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.20.mlp.fc2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.20.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.20.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.20.self_attn.out_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.20.self_attn.out_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.20.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.20.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.20.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.20.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.21.layer_norm1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.21.layer_norm1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.21.layer_norm2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.21.layer_norm2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.21.mlp.fc1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.21.mlp.fc1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.21.mlp.fc2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.21.mlp.fc2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.21.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.21.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.21.self_attn.out_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.21.self_attn.out_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.21.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.21.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.21.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.21.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.22.layer_norm1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.22.layer_norm1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.22.layer_norm2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.22.layer_norm2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.22.mlp.fc1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.22.mlp.fc1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.22.mlp.fc2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.22.mlp.fc2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.22.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.22.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.22.self_attn.out_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.22.self_attn.out_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.22.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.22.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.22.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.22.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.23.layer_norm1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.23.layer_norm1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.23.layer_norm2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.23.layer_norm2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.23.mlp.fc1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.23.mlp.fc1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.23.mlp.fc2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.23.mlp.fc2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.23.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.23.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.23.self_attn.out_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.23.self_attn.out_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.23.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.23.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.23.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.23.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.24.layer_norm1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.24.layer_norm1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.24.layer_norm2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.24.layer_norm2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.24.mlp.fc1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.24.mlp.fc1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.24.mlp.fc2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.24.mlp.fc2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.24.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.24.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.24.self_attn.out_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.24.self_attn.out_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.24.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.24.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.24.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.24.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.25.layer_norm1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.25.layer_norm1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.25.layer_norm2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.25.layer_norm2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.25.mlp.fc1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.25.mlp.fc1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.25.mlp.fc2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.25.mlp.fc2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.25.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.25.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.25.self_attn.out_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.25.self_attn.out_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.25.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.25.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.25.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.25.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.26.layer_norm1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.26.layer_norm1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.26.layer_norm2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.26.layer_norm2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.26.mlp.fc1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.26.mlp.fc1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.26.mlp.fc2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.26.mlp.fc2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.26.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.26.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.26.self_attn.out_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.26.self_attn.out_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.26.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.26.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.26.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.26.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.3.layer_norm1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.3.layer_norm1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.3.layer_norm2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.3.layer_norm2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.3.mlp.fc1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.3.mlp.fc1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.3.mlp.fc2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.3.mlp.fc2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.3.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.3.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.3.self_attn.out_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.3.self_attn.out_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.3.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.3.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.3.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.3.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.4.layer_norm1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.4.layer_norm1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.4.layer_norm2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.4.layer_norm2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.4.mlp.fc1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.4.mlp.fc1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.4.mlp.fc2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.4.mlp.fc2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.4.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.4.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.4.self_attn.out_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.4.self_attn.out_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.4.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.4.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.4.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.4.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.5.layer_norm1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.5.layer_norm1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.5.layer_norm2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.5.layer_norm2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.5.mlp.fc1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.5.mlp.fc1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.5.mlp.fc2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.5.mlp.fc2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.5.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.5.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.5.self_attn.out_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.5.self_attn.out_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.5.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.5.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.5.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.5.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.6.layer_norm1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.6.layer_norm1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.6.layer_norm2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.6.layer_norm2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.6.mlp.fc1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.6.mlp.fc1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.6.mlp.fc2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.6.mlp.fc2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.6.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.6.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.6.self_attn.out_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.6.self_attn.out_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.6.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.6.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.6.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.6.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.7.layer_norm1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.7.layer_norm1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.7.layer_norm2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.7.layer_norm2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.7.mlp.fc1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.7.mlp.fc1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.7.mlp.fc2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.7.mlp.fc2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.7.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.7.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.7.self_attn.out_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.7.self_attn.out_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.7.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.7.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.7.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.7.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.8.layer_norm1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.8.layer_norm1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.8.layer_norm2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.8.layer_norm2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.8.mlp.fc1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.8.mlp.fc1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.8.mlp.fc2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.8.mlp.fc2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.8.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.8.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.8.self_attn.out_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.8.self_attn.out_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.8.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.8.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.8.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.8.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.9.layer_norm1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.9.layer_norm1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.9.layer_norm2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.9.layer_norm2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.9.mlp.fc1.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.9.mlp.fc1.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.9.mlp.fc2.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.9.mlp.fc2.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.9.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.9.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.9.self_attn.out_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.9.self_attn.out_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.9.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.9.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.9.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.encoder.layers.9.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.post_layernorm.bias": "model-00001-of-00005.safetensors", + "vision_tower.vision_model.post_layernorm.weight": "model-00001-of-00005.safetensors" + } +} diff --git a/VRGDG_Musubi-tuner/models/gemma-3-12b-it/preprocessor_config.json b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/preprocessor_config.json new file mode 100644 index 0000000000000000000000000000000000000000..b1e00fc184f61b698181821169c6374cd5813e5c --- /dev/null +++ b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/preprocessor_config.json @@ -0,0 +1,29 @@ +{ + "do_convert_rgb": null, + "do_normalize": true, + "do_pan_and_scan": null, + "do_rescale": true, + "do_resize": true, + "image_mean": [ + 0.5, + 0.5, + 0.5 + ], + "image_processor_type": "Gemma3ImageProcessor", + "image_seq_length": 256, + "image_std": [ + 0.5, + 0.5, + 0.5 + ], + "pan_and_scan_max_num_crops": null, + "pan_and_scan_min_crop_size": null, + "pan_and_scan_min_ratio_to_activate": null, + "processor_class": "Gemma3Processor", + "resample": 2, + "rescale_factor": 0.00392156862745098, + "size": { + "height": 896, + "width": 896 + } +} diff --git a/VRGDG_Musubi-tuner/models/gemma-3-12b-it/processor_config.json b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/processor_config.json new file mode 100644 index 0000000000000000000000000000000000000000..453c7966d4b5d0b4a317c585989f64c58c2a6bf0 --- /dev/null +++ b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/processor_config.json @@ -0,0 +1,4 @@ +{ + "image_seq_length": 256, + "processor_class": "Gemma3Processor" +} diff --git a/VRGDG_Musubi-tuner/models/gemma-3-12b-it/special_tokens_map.json b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/special_tokens_map.json new file mode 100644 index 0000000000000000000000000000000000000000..1a6193244714d3d78be48666cb02cdbfac62ad86 --- /dev/null +++ b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/special_tokens_map.json @@ -0,0 +1,33 @@ +{ + "boi_token": "", + "bos_token": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false + }, + "eoi_token": "", + "eos_token": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false + }, + "image_token": "", + "pad_token": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false + }, + "unk_token": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false + } +} diff --git a/VRGDG_Musubi-tuner/models/gemma-3-12b-it/tokenizer.json b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/tokenizer.json new file mode 100644 index 0000000000000000000000000000000000000000..29401f984828a18bb09a6128d437c6766785eb66 --- /dev/null +++ b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/tokenizer.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4667f2089529e8e7657cfb6d1c19910ae71ff5f28aa7ab2ff2763330affad795 +size 33384568 diff --git a/VRGDG_Musubi-tuner/models/gemma-3-12b-it/tokenizer.model b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/tokenizer.model new file mode 100644 index 0000000000000000000000000000000000000000..14f810a829755bae3fafd6f97096dbd2eac556bd --- /dev/null +++ b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/tokenizer.model @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1299c11d7cf632ef3b4e11937501358ada021bbdf7c47638d13c0ee982f2e79c +size 4689074 diff --git a/VRGDG_Musubi-tuner/models/gemma-3-12b-it/tokenizer_config.json b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/tokenizer_config.json new file mode 100644 index 0000000000000000000000000000000000000000..7bdd14f0eaec30c8d2c56bc9d543587676e19c0f --- /dev/null +++ b/VRGDG_Musubi-tuner/models/gemma-3-12b-it/tokenizer_config.json @@ -0,0 +1,51346 @@ +{ + "add_bos_token": true, + "add_eos_token": false, + "added_tokens_decoder": { + "0": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "1": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "2": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "3": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "4": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "5": { + "content": "[multimodal]", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "6": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "7": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "8": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "9": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "10": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "11": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "12": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "13": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "14": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "15": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "16": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "17": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "18": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "19": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "20": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "21": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "22": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "23": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "24": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "25": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "26": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "27": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "28": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "29": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "30": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "31": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "32": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "33": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "34": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "35": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "36": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "37": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "38": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "39": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "40": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "41": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "42": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "43": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "44": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "45": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "46": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "47": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "48": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "49": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "50": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "51": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "52": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "53": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "54": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "55": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "56": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "57": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "58": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "59": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "60": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "61": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "62": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "63": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "64": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "65": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "66": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "67": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "68": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "69": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "70": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "71": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "72": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "73": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "74": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "75": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "76": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "77": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "78": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "79": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "80": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "81": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "82": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "83": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "84": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "85": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "86": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "87": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "88": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "89": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "90": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "91": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "92": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "93": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "94": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "95": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "96": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "97": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "98": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "99": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "100": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "101": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "102": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "103": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "104": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "105": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "106": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "107": { + "content": "\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "108": { + "content": "\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "109": { + "content": "\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "110": { + "content": "\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "111": { + "content": "\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "112": { + "content": "\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "113": { + "content": "\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "114": { + "content": "\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "115": { + "content": "\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "116": { + "content": "\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "117": { + "content": "\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "118": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "119": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "120": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "121": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "122": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "123": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "124": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "125": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "126": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "127": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "128": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "129": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "130": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "131": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "132": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "133": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "134": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "135": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "136": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "137": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "138": { + "content": "▁▁", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "139": { + "content": "▁▁▁", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "140": { + "content": "▁▁▁▁", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "141": { + "content": "▁▁▁▁▁", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "142": { + "content": "▁▁▁▁▁▁", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "143": { + "content": "▁▁▁▁▁▁▁", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "144": { + "content": "▁▁▁▁▁▁▁▁", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "145": { + "content": "▁▁▁▁▁▁▁▁▁", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "146": { + "content": "▁▁▁▁▁▁▁▁▁▁", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "147": { + "content": "▁▁▁▁▁▁▁▁▁▁▁", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "148": { + "content": "▁▁▁▁▁▁▁▁▁▁▁▁", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "149": { + "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "150": { + "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "151": { + "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "152": { + "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "153": { + "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "154": { + "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "155": { + "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "156": { + "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "157": { + "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "158": { + "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "159": { + "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "160": { + "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "161": { + "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "162": { + "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "163": { + "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "164": { + "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "165": { + "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "166": { + "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "167": { + "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "168": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "169": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "171": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "172": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "173": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "174": { + "content": "
", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "170": { + "content": "
", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "175": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "176": { + "content": "
", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "177": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "178": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "179": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "180": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "181": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "182": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "183": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "184": { + "content": "

", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "185": { + "content": "

", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "186": { + "content": "

", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "187": { + "content": "

", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "188": { + "content": "

", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "189": { + "content": "
", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "190": { + "content": "
", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "191": { + "content": "
", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "192": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "193": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "194": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "195": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "196": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "197": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "198": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "199": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "200": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "201": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "202": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "203": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "204": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "205": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "206": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "207": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "208": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "209": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "210": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "211": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "212": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "213": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "214": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "215": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "216": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "217": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "218": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "219": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "220": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "221": { + "content": "", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "222": { + "content": "