# コミュニティのパイプラインとコンポーネント

コミュニティのパイプラインは、元の論文の実装とは異なる[DiffusionPipeline](/docs/diffusers/v0.43.0/ja/api/pipelines/overview#diffusers.DiffusionPipeline)クラスです。追加の機能を提供したり、元のパイプライン実装を拡張したりします。

> [!TIP]
> 推論とトレーニングの例を含む、[diffusers/examples/community](https://github.com/huggingface/diffusers/tree/main/examples/community) のコミュニティ向けパイプラインを確認してください。

コミュニティのパイプラインは、Hub または Diffusers の GitHub リポジトリに保存されます。Hub のパイプラインは完全にカスタマイズ可能（スケジューラ、モデル、パイプラインコードなど）ですが、GitHub のパイプラインはカスタムパイプラインコードのみに限定されます。以下の表で、2 つのパイプラインタイプを比較してください。

|  | GitHub | Hub |
|---|---|---|
| 使用方法 | `custom_pipeline="<filename_without_.py>"` | `_class_name` がカスタムコードを指している場合の、Hub リポジトリ ID または `trust_remote_code=True` |
| レビュープロセス | GitHub で Pull Request を作成し、マージ前に Diffusers チームによるレビュープロセスを経る必要があります。このオプションは時間がかかります。 | レビューなしで Hub リポジトリに直接アップロードします。これが最も迅速な方法です。 |
| 可視性 | 公式のDiffusersリポジトリおよびドキュメントに収録されています。 | Hub プロファイルに含められ、ご自身の利用状況やプロモーションによって可視性が得られます。 |

## コミュニティのパイプラインの読み込み

`custom_pipeline` を [from_pretrained()](/docs/diffusers/v0.43.0/ja/api/pipelines/overview#diffusers.DiffusionPipeline.from_pretrained) に渡すことで、いずれかのタイプのコミュニティパイプラインを読み込むことができます。

```py
import torch
from diffusers import DiffusionPipeline

pipeline = DiffusionPipeline.from_pretrained(
    "stabilityai/stable-diffusion-3-medium-diffusers",
    custom_pipeline="pipeline_stable_diffusion_3_instruct_pix2pix",
    dtype=torch.float16,
    device_map="cuda"  # or "mps", "xpu", "cpu"
)
```

`custom_revision` 引数を [from_pretrained()](/docs/diffusers/v0.43.0/ja/api/pipelines/overview#diffusers.DiffusionPipeline.from_pretrained) に追加して、特定のバージョン（例: `v0.30.0` または `main`）からコミュニティのパイプラインを読み込みます。デフォルトでは、コミュニティのパイプラインは Diffusers の最新の安定版から読み込まれます。

```py
import torch
from diffusers import DiffusionPipeline

pipeline = DiffusionPipeline.from_pretrained(
    "stabilityai/stable-diffusion-3-medium-diffusers",
    custom_pipeline="pipeline_stable_diffusion_3_instruct_pix2pix",
    custom_revision="main",
    dtype=torch.float16,
    device_map="cuda"  # or "mps", "xpu", "cpu"
)
```

> [!WARNING]
> Hugging Face Hub がファイルを[スキャン](https://huggingface.co/docs/hub/security-malware)している間でも、Hub のパイプラインコードを確認し、安全であることが保証されていることを確認する必要があります。

コミュニティのパイプラインを読み込む方法はいくつかあります。

- `custom_pipeline` にパスを渡すことで、ローカルのコミュニティパイプラインを読み込むことができます。ディレクトリには、パイプラインクラスを含む `pipeline.py` ファイルが必要です。

  ```py
  import torch
  from diffusers import DiffusionPipeline

  pipeline = DiffusionPipeline.from_pretrained(
      "stabilityai/stable-diffusion-3-medium-diffusers",
      custom_pipeline="path/to/pipeline_directory",
      trust_remote_code=True,
      dtype=torch.float16,
      device_map="cuda"  # or "mps", "xpu", "cpu"
  )
  ```

- `custom_pipeline` 引数は [from_pipe()](/docs/diffusers/v0.43.0/ja/api/pipelines/overview#diffusers.DiffusionPipeline.from_pipe) によってもサポートされており、[パイプラインの再利用](./loading#reusing-models-in-multiple-pipelines) に有用です。これにより、追加のメモリを使用せずにパイプラインを再利用できます。メモリ使用量は、読み込まれたパイプラインのうち最大のものに限定されます。

  ```py
  import torch
  from diffusers import DiffusionPipeline

  pipeline_sd = DiffusionPipeline.from_pretrained(
      "emilianJR/CyberRealistic_V3", dtype=torch.float16, device_map="cuda"  # or "mps", "xpu", "cpu"
  )
  pipeline_lpw = DiffusionPipeline.from_pipe(
      pipeline_sd, custom_pipeline="lpw_stable_diffusion"
  )
  ```

  [from_pipe()](/docs/diffusers/v0.43.0/ja/api/pipelines/overview#diffusers.DiffusionPipeline.from_pipe) メソッドは、コミュニティのパイプラインを読み込む際に特に有用です。多くのコミュニティのパイプラインには事前学習済み重みが含まれていないためです。コミュニティのパイプラインは、既存のパイプラインの上に機能を追加するものが一般的です。

## コミュニティコンポーネント

Community components は、Diffusers がサポートしていないカスタムな transformers、UNet、VAE、スケジューラーを使用してパイプラインを構築できます。これらのコンポーネントには、それぞれ独自の Python モジュールが必要です。

このセクションでは、[showlab/show-1-base](https://huggingface.co/showlab/show-1-base) を例として、コミュニティのコンポーネントを使用してコミュニティのパイプラインを構築する方法を示します。

1. 必要なコンポーネントであるスケジューラと画像プロセッサを読み込みます。テキストエンコーダーは通常、[Transformers](https://huggingface.co/docs/transformers/index)からインポートされます。

```python
from transformers import T5Tokenizer, T5EncoderModel, CLIPImageProcessor
from diffusers import DPMSolverMultistepScheduler

pipeline_id = "showlab/show-1-base"
tokenizer = T5Tokenizer.from_pretrained(pipeline_id, subfolder="tokenizer")
text_encoder = T5EncoderModel.from_pretrained(pipeline_id, subfolder="text_encoder")
scheduler = DPMSolverMultistepScheduler.from_pretrained(pipeline_id, subfolder="scheduler")
feature_extractor = CLIPImageProcessor.from_pretrained(pipeline_id, subfolder="feature_extractor")
```

> [!WARNING]
> ステップ2と3では、この例が動作するために、カスタムの[UNet](https://github.com/showlab/Show-1/blob/main/showone/models/unet_3d_condition.py)および[pipeline](https://huggingface.co/sayakpaul/show-1-base-with-code/blob/main/unet/showone_unet_3d_condition.py)の実装が、それぞれのファイルに示されている形式と一致している必要があります。

2. [カスタム UNet](https://github.com/showlab/Show-1/blob/main/showone/models/unet_3d_condition.py)を読み込みます。これは既に[showone_unet_3d_condition.py](https://huggingface.co/sayakpaul/show-1-base-with-code/blob/main/unet/showone_unet_3d_condition.py)に実装されています。[UNet3DConditionModel](/docs/diffusers/v0.43.0/ja/api/models/unet3d-cond#diffusers.UNet3DConditionModel)のクラス名は、Diffusers に[UNet3DConditionModel](/docs/diffusers/v0.43.0/ja/api/models/unet3d-cond#diffusers.UNet3DConditionModel)が既に存在するため、カスタム実装である`ShowOneUNet3DConditionModel`に変更されています。`ShowOneUNet3DConditionModel`クラスに必要なコンポーネントはすべて`showone_unet_3d_condition.py`に配置してください。

```python
from showone_unet_3d_condition import ShowOneUNet3DConditionModel

unet = ShowOneUNet3DConditionModel.from_pretrained(pipeline_id, subfolder="unet")
```

3. カスタムパイプラインのコード（[pipeline_t2v_base_pixel.py](https://huggingface.co/sayakpaul/show-1-base-with-code/blob/main/pipeline_t2v_base_pixel.py) に実装済み）を読み込みます。このスクリプトには、テキストから動画を生成するためのカスタム `TextToVideoIFPipeline` クラスが含まれています。カスタム UNet と同様に、`TextToVideoIFPipeline` に必要なコードはすべて `pipeline_t2v_base_pixel.py` に配置する必要があります。

`ShowOneUNet3DConditionModel` を使用して `TextToVideoIFPipeline` を初期化します。

```python
import torch
from pipeline_t2v_base_pixel import TextToVideoIFPipeline

pipeline = TextToVideoIFPipeline(
    unet=unet,
    text_encoder=text_encoder,
    tokenizer=tokenizer,
    scheduler=scheduler,
    feature_extractor=feature_extractor,
)
pipeline = pipeline.to("cuda")  # or "mps", "xpu", "cpu"
```

4. パイプラインをHubにプッシュして、コミュニティと共有します。

```python
pipeline.push_to_hub("custom-t2v-pipeline")
```

パイプラインが正常にプッシュされた後、以下の変更を行ってください。

- `_class_name` 属性を [model_index.json](https://huggingface.co/sayakpaul/show-1-base-with-code/blob/main/model_index.json#L2) 内で `["pipeline_t2v_base_pixel", "TextToVideoIFPipeline"]` に変更してください。
- `showone_unet_3d_condition.py` を [unet](https://huggingface.co/sayakpaul/show-1-base-with-code/blob/main/unet/showone_unet_3d_condition.py) サブフォルダーにアップロードしてください。
- パイプライン[リポジトリ](https://huggingface.co/sayakpaul/show-1-base-with-code/tree/main)に`pipeline_t2v_base_pixel.py`をアップロードしてください。

推論を実行するには、パイプラインを初期化する際に`trust_remote_code`引数を追加し、裏側で行われるすべての「マジック」を処理します。

```python
import torch
from diffusers import DiffusionPipeline

pipeline = DiffusionPipeline.from_pretrained(
    "<change-username>/<change-id>", trust_remote_code=True, dtype=torch.float16
)
```

> [!WARNING]
> `trust_remote_code=True` を使用する場合の追加の安全対策として、[from_pretrained()](/docs/diffusers/v0.43.0/ja/api/pipelines/overview#diffusers.DiffusionPipeline.from_pretrained) の `revision` 引数にコミットハッシュを渡すことで、コードが新しい悪意あるコードで更新されていないことを確認してください（モデルの所有者を完全に信頼している場合を除く）。

## 次のステップ

- コミュニティのパイプラインを追加する理由について、より詳しい背景は Issue [#841](https://github.com/huggingface/diffusers/issues/841) をご覧ください。これにより、すべてのユーザーが作業をスムーズに共有できるようになります。
- コミュニティのパイプラインの追加の例として、`trust_remote_code` 機能も使用している [stabilityai/japanese-stable-diffusion-xl](https://huggingface.co/stabilityai/japanese-stable-diffusion-xl/) リポジトリをご覧ください。

