# モデル形式

Diffusionモデルは、通常、Diffusers形式または単一ファイル形式で保存されます。モデルファイルは、safetensorsやckptなどのさまざまなファイル形式で保存できます。

> [!TIP]
> Format は、重みがディレクトリ構造で保存されているかどうかを指します。File type は、その重みがどのようにシリアライズされるか（safetensors や ckpt など）を指します。

```text
Diffusers format                    Single-file format
model/                              model.safetensors   (or .ckpt)
├─ model_index.json                 └─ all components in one file
├─ unet/  (or transformer/)
├─ text_encoder/
├─ vae/
└─ scheduler/
```

このガイドでは、これらの形式およびファイルからパイプラインとモデルを読み込む方法を紹介します。

## Diffusers形式

Diffusers形式では、各モデル（UNet、transformer、text encoder）が個別のサブフォルダーに保存されます。モデルを個別に保存することにはいくつかの利点があります。

- 必要な個別モデルのみを読み込むか、すべてを並列で読み込むことができるため、パイプライン全体の初期化が高速になります。
- 必要なモデルが1つだけの場合、すべてのパイプラインコンポーネントを読み込む必要がないため、メモリ使用量が削減されます。複数のパイプラインで共有されるモデルを[再利用](./loading#reusing-models-in-multiple-pipelines)できます。
- 複数のパイプラインで共有される共通モデルは一度だけダウンロードされるため、ストレージ要件が低減されます。
- パイプライン内で新しいモデルや改良されたモデルを使用できる柔軟性。

## 単一ファイル形式

単一ファイル形式では、*すべての*モデルの重み（UNet、transformer、text encoder）が1つのファイルに保存されます。単一ファイル形式の利点は以下の通りです。

- [ComfyUI](https://github.com/comfyanonymous/ComfyUI) や [Automatic1111](https://github.com/AUTOMATIC1111/stable-diffusion-webui) との互換性が向上しました。
- 単一のファイルをダウンロード・共有しやすくなります。

単一ファイルを読み込むには、[from_single_file()](/docs/diffusers/main/ja/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file)を使用します。

```py
import torch
from diffusers import StableDiffusionXLPipeline

pipeline = StableDiffusionXLPipeline.from_single_file(
    "https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/blob/main/sd_xl_base_1.0.safetensors",
    dtype=torch.float16,
    device_map="cuda"  # or "mps", "xpu", "cpu"
)
```

[from_single_file()](/docs/diffusers/main/ja/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file) メソッドは、新しいモデルやスケジューラーを渡すこともサポートしています。

```py
import torch
from diffusers import FluxPipeline, FluxTransformer2DModel

transformer = FluxTransformer2DModel.from_single_file(
    "https://huggingface.co/Kijai/flux-fp8/blob/main/flux1-dev-fp8.safetensors", dtype=torch.bfloat16
)
pipeline = FluxPipeline.from_pretrained(
    "black-forest-labs/FLUX.1-dev",
    transformer=transformer,
    dtype=torch.bfloat16,
    device_map="cuda"  # or "mps", "xpu", "cpu"
)
```

### 設定オプション

Diffusers形式のモデルには、レイヤー数やアテンションヘッド数などの重要な属性が記載された`config.json`ファイルがリポジトリに存在します。[from_single_file()](/docs/diffusers/main/ja/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file)メソッドは、`config.json`から使用する適切なconfigを自動的に決定します。ただし、まれにこの処理が失敗する場合があります。その場合は、`config`引数を使用してください。

パイプライン内のモデルが元の実装と異なる場合、または正しい設定を決定するために必要なメタデータがない場合も、`config` 引数を使用する必要があります。

```py
from diffusers import StableDiffusionXLPipeline

ckpt_path = "https://huggingface.co/segmind/SSD-1B/blob/main/SSD-1B.safetensors"

pipeline = StableDiffusionXLPipeline.from_single_file(ckpt_path, config="segmind/SSD-1B")
```

`original_config` に `local_files_only=True` を渡すと、Diffusers はパイプラインクラスのシグネチャからパイプラインのコンポーネントを推論します。この場合、Hub から設定ファイルをダウンロードしないため、オフライン環境での破壊的変更を回避できます。ただし、`config` にローカルモデルのパスを指定するよりも信頼性が低く、エラーが発生する可能性があります。後でオフライン環境で設定ファイルが必要になる場合は、一度 `local_files_only=False` で実行し、設定ファイルをローカルキャッシュに保存しておいてください。

引数を[from_single_file()](/docs/diffusers/main/ja/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file)に直接渡すことで、デフォルトの構成を上書きできます。以下の例では、パイプラインまたはモデルの構成を上書きする方法を示しています。

```py
from diffusers import StableDiffusionXLInstructPix2PixPipeline

ckpt_path = "https://huggingface.co/stabilityai/cosxl/blob/main/cosxl_edit.safetensors"
pipeline = StableDiffusionXLInstructPix2PixPipeline.from_single_file(
    ckpt_path, config="diffusers/sdxl-instructpix2pix-768", is_cosxl_edit=True
)
```

```py
from diffusers import UNet2DConditionModel

ckpt_path = "https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/blob/main/sd_xl_base_1.0_0.9vae.safetensors"
model = UNet2DConditionModel.from_single_file(ckpt_path, upcast_attention=True)
```

### ローカルファイル

[from_single_file()](/docs/diffusers/main/ja/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file) メソッドは、チェックポイントファイル内のキーからモデルタイプを推論することにより、パイプラインまたはモデルを設定しようとします。例えば、Stable Diffusion XL ベースモデルに基づく単一ファイルのチェックポイントは、[stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0) から設定されます。

ローカルファイルで作業する場合は、[snapshot_download](https://huggingface.co/docs/huggingface_hub/main/en/package_reference/file_download#huggingface_hub.snapshot_download) メソッドで設定ファイルを、[hf_hub_download](https://huggingface.co/docs/huggingface_hub/main/en/package_reference/file_download#huggingface_hub.hf_hub_download) でモデルのチェックポイントをダウンロードします。これらのファイルは[キャッシュディレクトリ](https://huggingface.co/docs/huggingface_hub/en/guides/manage-cache)にダウンロードされますが、`local_dir` 引数を使用して特定のディレクトリにダウンロードすることもできます。

```py
from huggingface_hub import hf_hub_download, snapshot_download
from diffusers import StableDiffusionXLPipeline

my_local_checkpoint_path = hf_hub_download(
    repo_id="segmind/SSD-1B",
    filename="SSD-1B.safetensors"
)

my_local_config_path = snapshot_download(
    repo_id="segmind/SSD-1B",
    allow_patterns=["*.json", "**/*.json", "*.txt", "**/*.txt"]
)

pipeline = StableDiffusionXLPipeline.from_single_file(
    my_local_checkpoint_path, config=my_local_config_path, local_files_only=True
)
```

### シンボリックリンク

シンボリックリンクをサポートしないファイルシステムで作業している場合は、まず`local_dir`パラメータを使用してチェックポイントファイルをローカルディレクトリにダウンロードしてください。`local_dir`パラメータを使用すると、シンボリックリンクは自動的に無効になります。

```py
from huggingface_hub import hf_hub_download, snapshot_download
from diffusers import StableDiffusionXLPipeline

my_local_checkpoint_path = hf_hub_download(
    repo_id="segmind/SSD-1B",
    filename="SSD-1B.safetensors",
    local_dir="my_local_checkpoints",
)
print("My local checkpoint: ", my_local_checkpoint_path)

my_local_config_path = snapshot_download(
    repo_id="segmind/SSD-1B",
    allow_patterns=["*.json", "**/*.json", "*.txt", "**/*.txt"]
)
print("My local config: ", my_local_config_path)
```

これらのパスを[from_single_file()](/docs/diffusers/main/ja/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file)に渡します。

```py
pipeline = StableDiffusionXLPipeline.from_single_file(
    my_local_checkpoint_path, config=my_local_config_path, local_files_only=True
)
```

## ファイルの種類

モデルは複数のファイル形式で保存できます。Safetensorsが最も一般的なファイル形式ですが、Hubや拡散モデルコミュニティでは他のファイル形式にも遭遇する可能性があります。

### safetensors

[Safetensors](https://hf.co/docs/safetensors) は、テンソルを安全かつ高速に保存・読み込むためのファイル形式です。ヘッダーサイズに制限を設けることで特定の攻撃を制限し、遅延読み込み（分散環境で有用）をサポートし、一般的に読み込みが高速です。

Safetensors ライブラリがインストールされており、safetensors ファイルが利用可能な場合、Diffusers はデフォルトで safetensors ファイルを読み込みます（必須の依存関係）。

Use [from_pretrained()](/docs/diffusers/main/ja/api/pipelines/overview#diffusers.DiffusionPipeline.from_pretrained) or [from_single_file()](/docs/diffusers/main/ja/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file) to load safetensor files.

```py
import torch
from diffusers import DiffusionPipeline, StableDiffusionXLPipeline

pipeline = DiffusionPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    dtype=torch.float16,
    device_map="cuda",  # or "mps", "xpu", "cpu"
)

pipeline = StableDiffusionXLPipeline.from_single_file(
    "https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/blob/main/sd_xl_base_1.0.safetensors",
    dtype=torch.float16,
)
```

Diffusersの学習スクリプトで学習されたチェックポイントを使用している場合、LoRA設定などのメタデータは自動的に保存されます。ファイルを読み込むと、そのメタデータが解析され、LoRAが正しく設定されます。Hub上のファイルの横にある  アイコンをクリックして、safetensorsファイルのメタデータを確認できます。

Diffusers で学習されていないチェックポイントの LoRA アダプターメタデータを保存するには、[save_lora_weights()](/docs/diffusers/main/ja/api/loaders/lora#diffusers.loaders.FluxLoraLoaderMixin.save_lora_weights) にメタデータを渡します。transformer には `transformer_lora_adapter_metadata` を、テキストエンコーダーには `text_encoder_lora_adapter_metadata` を使用します。また、`save_directory` と、`transformer_lora_layers` または `text_encoder_lora_layers` の少なくとも一方を渡す必要があります。このパスは safetensors ファイルのみサポートされています。

```py
import torch
from peft.utils import get_peft_model_state_dict
from diffusers import FluxPipeline

pipeline = FluxPipeline.from_pretrained(
    "black-forest-labs/FLUX.1-dev", dtype=torch.bfloat16, device_map="cuda"  # or "mps", "xpu", "cpu"
)
pipeline.load_lora_weights("linoyts/yarn_art_Flux_LoRA")

transformer_lora_layers = get_peft_model_state_dict(pipeline.transformer)
pipeline.save_lora_weights(
    save_directory="path/to/lora",
    transformer_lora_layers=transformer_lora_layers,
    transformer_lora_adapter_metadata={"r": 8, "lora_alpha": 8},
)
```

### ckpt

古いモデルの重みは、通常、Pythonの[pickle](https://docs.python.org/3/library/pickle.html)ユーティリティを使用してckptファイルに保存されます。

ピクルス形式のファイルは、悪意のあるコードの実行に悪用される可能性があるため、安全ではありません。safetensors形式のファイルを使用するか、重みをsafetensors形式に変換することをお勧めします。

[from_single_file()](/docs/diffusers/main/ja/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file)を使用してckptファイルを読み込みます。

```py
from diffusers import StableDiffusionPipeline

pipeline = StableDiffusionPipeline.from_single_file(
    "https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5/blob/main/v1-5-pruned.ckpt"
)
```

### GGUF

GGUFは、量子化済みの重みを単一のファイルに格納します。Diffusersは、[GGUFQuantizationConfig](/docs/diffusers/main/ja/api/quantization#diffusers.GGUFQuantizationConfig) を使用して、モデルの [from_single_file()](/docs/diffusers/main/ja/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file) 経由で GGUF を読み込みます。パイプラインレベルでの GGUF の読み込みはサポートされていません。

インストール手順と完全な例については、[GGUF](../quantization/gguf)を参照してください。

```py
import torch
from diffusers import FluxTransformer2DModel, GGUFQuantizationConfig

transformer = FluxTransformer2DModel.from_single_file(
    "https://huggingface.co/city96/FLUX.1-dev-gguf/blob/main/flux1-dev-Q2_K.gguf",
    quantization_config=GGUFQuantizationConfig(compute_dtype=torch.bfloat16),
)
```

## 形式とファイルの変換

Diffusers は、フォーマットやファイルの変換を行うスクリプトとメソッドを提供しており、拡散モデルのエコシステム内のより多くのツールがこれらを利用できるようにします。

[diffusers/scripts](https://github.com/huggingface/diffusers/tree/main/scripts) フォルダを確認すると、変換スクリプトが見つかります。`"to_diffusers"` が末尾に付加されたスクリプトは、モデルを Diffusers 形式に変換します。各スクリプトには、変換を設定するための固有の引数が用意されています。利用可能な引数を確認してください。

以下の例では、Diffusers形式で保存されたモデルを単一ファイル形式に変換します。変換するモデルのパスと、変換後のモデルを保存する場所を指定してください。オプションとして、モデルを保存するファイル形式とデータ型を指定することもできます。

```bash
python convert_diffusers_to_original_sdxl.py --model_path path/to/model/to/convert --checkpoint_path path/to/save/model/to --use_safetensors
```

[save_pretrained()](/docs/diffusers/main/ja/api/pipelines/overview#diffusers.DiffusionPipeline.save_pretrained) メソッドは、モデルを Diffusers 形式で保存し、各モデル用のサブフォルダーの作成も処理します。デフォルトでは、ファイルを safetensor 形式で保存します。

```py
from diffusers import StableDiffusionXLPipeline

pipeline = StableDiffusionXLPipeline.from_single_file(
    "https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/blob/main/sd_xl_base_1.0.safetensors",
)
pipeline.save_pretrained("path/to/save/model")
```

## 次のステップ

- [本当に安全と監査され、標準になりつつあるSafetensors](https://blog.eleuther.ai/safetensors-security-audit/)のブログ記事で、設計上の判断や、モデルの重みを保存・読み込む際にsafetensorファイルが推奨される理由について詳しく学んでください。

