# LoRA Training Guide for MOSS-Image using `moss_image_train_network.py` / `moss_image_train_network.py` を用いた MOSS-Image モデルの LoRA 学習ガイド
This document explains how to train LoRA (Low-Rank Adaptation) models for MOSS-Image using `moss_image_train_network.py` in the `sd-scripts` repository.
日本語
このドキュメントでは、`sd-scripts` リポジトリに含まれる `moss_image_train_network.py` を使用して、MOSS-Image モデルに対する LoRA (Low-Rank Adaptation) モデルを学習する基本的な手順について解説します。
## 1. Introduction / はじめに
`moss_image_train_network.py` trains additional networks such as LoRA for [MOSS-Image](https://github.com/OpenMOSS/MOSS-Image) models (OpenMOSS). MOSS-Image is a 5B single-stream DiT (Diffusion Transformer, 42 blocks) trained with Rectified Flow. It uses Qwen3.5-9B as the text encoder (the last hidden state, 4096 dimensions, is fed to the DiT) and the FLUX.2 VAE (32-channel latent space, 8x spatial downscale). The DiT patchifies the latents 2x2, so the effective downscale of the image is 16x.
This guide assumes you already understand the basics of LoRA training. For common usage and options, see the [train_network.py guide](train_network.md). Many options are shared with [`anima_train_network.py`](anima_train_network.md) and [`flux_train_network.py`](flux_train_network.md).
**Prerequisites:**
* The `sd-scripts` repository has been cloned and the Python environment is ready.
* A training dataset has been prepared. See the [Dataset Configuration Guide](./config_README-en.md).
* MOSS-Image model files for training are available.
日本語
`moss_image_train_network.py` は、[MOSS-Image](https://github.com/OpenMOSS/MOSS-Image)(OpenMOSS)モデルに対して LoRA などの追加ネットワークを学習させるためのスクリプトです。MOSS-Image は Rectified Flow で学習された 5B の single-stream DiT (Diffusion Transformer、42 ブロック) です。テキストエンコーダーとして Qwen3.5-9B(最終層の hidden state、4096 次元を DiT に入力)、VAE として FLUX.2 VAE(32 チャンネル潜在空間、8 倍空間ダウンスケール)を使用します。DiT は潜在変数を 2x2 で patchify するため、画像に対する実効的なダウンスケールは 16 倍です。
このガイドは、LoRA 学習の基本を理解している方を対象としています。共通の使い方やオプションについては [train_network.py のガイド](train_network.md) を参照してください。多くのオプションは [`anima_train_network.py`](anima_train_network.md) や [`flux_train_network.py`](flux_train_network.md) と共通です。
**前提条件:**
* `sd-scripts` リポジトリのクローンと Python 環境のセットアップが完了していること。
* 学習用データセットの準備が完了していること。([データセット設定ガイド](./config_README-ja.md) を参照してください。)
* 学習対象の MOSS-Image モデルファイルが準備できていること。
## 2. Differences from `train_network.py` / `train_network.py` との違い
`moss_image_train_network.py` is based on `train_network.py` but modified for MOSS-Image. Main differences are:
* **Target models:** MOSS-Image DiT models (Base and SFT).
* **Model structure:** Uses a single-stream DiT instead of U-Net. Employs a single text encoder (Qwen3.5-9B) and the FLUX.2 VAE. The text encoder is bf16 and the VAE is fp32 regardless of `--mixed_precision`.
* **Arguments:** Uses the common `--pretrained_model_name_or_path` for the DiT model path, `--text_encoder` for the Qwen3.5-9B text encoder, and `--vae` for the FLUX.2 VAE.
* **Incompatible arguments:** Stable Diffusion v1/v2 options such as `--v2`, `--v_parameterization` and `--clip_skip` are not used. `--fp8_base` / `--fp8_base_unet` are not supported; use ConvRot INT8 (`--convrot_int8`) instead.
* **Timestep sampling:** Uses the same `--timestep_sampling` options as FLUX / Anima training (`sigma`, `uniform`, `sigmoid`, `shift`, `flux_shift`). The pre-training distribution of MOSS-Image can be reproduced with existing options (see [Section 7.2](#72-training-settings--学習設定)).
* **LoRA:** Uses the generic LoRA module `networks.lora_generic` with regex-based module selection and per-module rank/learning rate control (`network_reg_dims`, `network_reg_lrs`). Module exclusion/inclusion is controlled by `exclude_patterns` and `include_patterns`.
* **Text Encoder:** The text encoder is run one sample at a time without padding (the Qwen3.5 Gated DeltaNet layers are sensitive to padding), the same as the official pipeline. Captions can contain line breaks (`enable_multiline_caption`).
* **Caption dropout with cached text encoder outputs:** The unconditional embedding is stored in every cache file, so `caption_dropout_rate` works together with `--cache_text_encoder_outputs`.
* **Multiple caption candidates with cached text encoder outputs:** The outputs of all caption candidates of an image (`enable_multiline_caption` with separator lines) are stored in one cache file, and one of them is chosen randomly at each step. See [Section 3](#3-preparation--準備).
日本語
`moss_image_train_network.py` は `train_network.py` をベースに、MOSS-Image モデルに対応するための変更が加えられています。主な違いは以下の通りです。
* **対象モデル:** MOSS-Image の DiT モデル(Base および SFT)を対象とします。
* **モデル構造:** U-Net の代わりに single-stream DiT を使用します。テキストエンコーダーは Qwen3.5-9B の 1 つ、VAE は FLUX.2 VAE です。`--mixed_precision` の指定に関係なく、テキストエンコーダーは bf16、VAE は fp32 で動作します。
* **引数:** DiT モデルのパスには共通引数 `--pretrained_model_name_or_path` を、Qwen3.5-9B テキストエンコーダーには `--text_encoder` を、FLUX.2 VAE には `--vae` を使用します。
* **一部引数の非互換性:** Stable Diffusion v1/v2 向けの引数(例: `--v2`, `--v_parameterization`, `--clip_skip`)は使用されません。`--fp8_base` / `--fp8_base_unet` はサポートされません。代わりに ConvRot INT8(`--convrot_int8`)を使用してください。
* **タイムステップサンプリング:** FLUX / Anima 学習と同じ `--timestep_sampling` オプション(`sigma`、`uniform`、`sigmoid`、`shift`、`flux_shift`)を使用します。MOSS-Image の事前学習の分布は既存オプションの組み合わせで再現できます([7.2 節](#72-training-settings--学習設定) を参照)。
* **LoRA:** 汎用 LoRA モジュール `networks.lora_generic` を使用し、正規表現ベースのモジュール選択とモジュール単位のランク/学習率制御(`network_reg_dims`、`network_reg_lrs`)を行います。モジュールの除外/包含は `exclude_patterns` と `include_patterns` で制御します。
* **テキストエンコーダー:** 公式パイプラインと同様に、パディングなしで 1 サンプルずつ実行します(Qwen3.5 の Gated DeltaNet 層はパディングの影響を受けます)。キャプションには改行を含められます(`enable_multiline_caption`)。
* **キャッシュ時のキャプションドロップアウト:** 各キャッシュファイルに unconditional の埋め込みも保存するため、`caption_dropout_rate` を `--cache_text_encoder_outputs` と併用できます。
* **キャッシュ時の複数キャプション候補:** 画像の全キャプション候補(`enable_multiline_caption` と区切り行)の出力を一つのキャッシュファイルに保存し、ステップごとにランダムに一つを選びます。[3 節](#3-preparation--準備)を参照してください。
## 3. Preparation / 準備
The following files are required before starting training:
1. **Training script:** `moss_image_train_network.py`
2. **MOSS-Image DiT model file:** Either of the following. Specify the path with `--pretrained_model_name_or_path`.
* The official diffusers-format shards (`transformer/diffusion_pytorch_model-0000X-of-00003.safetensors` in the [OpenMOSS-Team/MOSS-Image-Base](https://huggingface.co/OpenMOSS-Team/MOSS-Image-Base) repository). **Specify the first shard** (`...-00001-of-00003.safetensors`); the other shards in the same directory are loaded automatically. `index.json` is not used.
* The ComfyUI single-file checkpoints (`moss_image_base_bf16.safetensors`, `moss_image_base_int8_convrot.safetensors`, and the `sft` variants). The ConvRot INT8 files are detected automatically (see [Section 7.1](#71-vram-usage-optimization--vram-使用量の最適化)).
3. **Qwen3.5-9B text encoder:** Either of the following. Specify the path with `--text_encoder`.
* The official shards (`text_encoder/model-0000X-of-00004.safetensors`). **Specify the first shard** (`model-00001-of-00004.safetensors`).
* The ComfyUI ConvRot INT8 file (`qwen3.5_9b_int8_convrot.safetensors`). The W4A8 GPTQ file (`qwen3.5_9b_w4a8_gptq.safetensors`) is **not** supported.
* The vision tower of Qwen3.5 is not loaded. The model config is bundled in `configs/moss_image_qwen35_9b/`.
4. **FLUX.2 VAE model file:** The ComfyUI / BFL format `flux2-vae.safetensors` is recommended. The diffusers-format VAE in the official repository (`vae/`, FLUX.2 "small decoder") can also be used; both share the same latent space, so cached latents are interchangeable. Specify the path with `--vae`.
5. **Tokenizer:** Downloaded automatically from the Hugging Face Hub (`OpenMOSS-Team/MOSS-Image-Base`, subfolder `tokenizer`, about 20MB). For offline training, specify `--tokenizer_cache_dir` with either a Hugging Face cache directory or a local directory containing the tokenizer files (`tokenizer_config.json` etc.).
6. **Dataset definition file (.toml):** Dataset settings in TOML format. (See the [Dataset Configuration Guide](./config_README-en.md).) In this document we use `my_moss_dataset_config.toml` as an example.
**Notes:**
* The bucket resolutions must be multiples of 16 (`bucket_reso_steps` of 16, 32, 64, ... The default 64 is fine).
* MOSS-Image is trained with long natural-language captions written by an LLM. `enable_multiline_caption = true` in the dataset config lets you use captions that contain line breaks as they are. See [the dataset config documentation](./config_README-en.md#captions-with-line-breaks-and-multiple-caption-candidates-enable_multiline_caption--true).
* Multiple caption candidates for one image (separator lines with `enable_multiline_caption`, e.g. an original caption and recaptions of different lengths, as in the official training) can be used together with `--cache_text_encoder_outputs`: all candidates are encoded and stored in one cache file, and one of them is chosen randomly at each step. The cache size and the caching time are multiplied by the number of candidates.
日本語
学習を開始する前に、以下のファイルが必要です。
1. **学習スクリプト:** `moss_image_train_network.py`
2. **MOSS-Image DiT モデルファイル:** 以下のいずれか。`--pretrained_model_name_or_path` にパスを指定します。
* 公式の diffusers 形式の分割ファイル([OpenMOSS-Team/MOSS-Image-Base](https://huggingface.co/OpenMOSS-Team/MOSS-Image-Base) リポジトリの `transformer/diffusion_pytorch_model-0000X-of-00003.safetensors`)。**最初のファイル**(`...-00001-of-00003.safetensors`)を指定してください。同じディレクトリの残りのファイルは自動的に読み込まれます。`index.json` は使用しません。
* ComfyUI 向けの単一ファイル(`moss_image_base_bf16.safetensors`、`moss_image_base_int8_convrot.safetensors`、および `sft` 版)。ConvRot INT8 のファイルは自動判別されます([7.1 節](#71-vram-usage-optimization--vram-使用量の最適化) を参照)。
3. **Qwen3.5-9B テキストエンコーダー:** 以下のいずれか。`--text_encoder` にパスを指定します。
* 公式の分割ファイル(`text_encoder/model-0000X-of-00004.safetensors`)。**最初のファイル**(`model-00001-of-00004.safetensors`)を指定してください。
* ComfyUI 向けの ConvRot INT8 ファイル(`qwen3.5_9b_int8_convrot.safetensors`)。W4A8 GPTQ のファイル(`qwen3.5_9b_w4a8_gptq.safetensors`)は**サポートされません**。
* Qwen3.5 の vision tower は読み込まれません。モデルの config は `configs/moss_image_qwen35_9b/` に同梱されています。
4. **FLUX.2 VAE モデルファイル:** ComfyUI / BFL 形式の `flux2-vae.safetensors` を推奨します。公式リポジトリの diffusers 形式 VAE(`vae/`、FLUX.2 の "small decoder" 版)も使用できます。両者の潜在空間は同一なので、latent のキャッシュは共用できます。`--vae` にパスを指定します。
5. **トークナイザー:** Hugging Face Hub(`OpenMOSS-Team/MOSS-Image-Base` の `tokenizer` サブフォルダ、約 20MB)から自動的にダウンロードされます。オフラインで学習する場合は、`--tokenizer_cache_dir` に Hugging Face のキャッシュディレクトリ、またはトークナイザーのファイル(`tokenizer_config.json` 等)を含むローカルディレクトリを指定してください。
6. **データセット定義ファイル (.toml):** 学習データセットの設定を記述した TOML 形式のファイル。(詳細は [データセット設定ガイド](./config_README-ja.md) を参照してください。)例として `my_moss_dataset_config.toml` を使用します。
**注意:**
* bucket の解像度は 16 の倍数である必要があります(`bucket_reso_steps` は 16、32、64 など。デフォルトの 64 で問題ありません)。
* MOSS-Image は LLM が書いた長い自然文のキャプションで学習されています。データセット設定で `enable_multiline_caption = true` を指定すると、改行を含むキャプションをそのまま使用できます。[データセット設定のドキュメント](./config_README-ja.md) を参照してください。
* 一つの画像に対する複数のキャプション候補(`enable_multiline_caption` の区切り行。公式の学習のように元のキャプションと長さの異なる再キャプションを用意する場合など)は、`--cache_text_encoder_outputs` と併用できます。全候補をエンコードして一つのキャッシュファイルに保存し、ステップごとにランダムに一つを選びます。キャッシュのサイズとキャッシュ時間は候補数倍になります。
## 4. Running the Training / 学習の実行
Execute `moss_image_train_network.py` from the terminal to start training. The overall command-line format is the same as `train_network.py`, but MOSS-Image specific options must be supplied.
Example command (DiT LoRA with cached text encoder outputs):
```bash
accelerate launch --num_cpu_threads_per_process 1 moss_image_train_network.py \
--pretrained_model_name_or_path="" \
--text_encoder="" \
--vae="" \
--dataset_config="my_moss_dataset_config.toml" \
--output_dir="