> ## Documentation Index
> Fetch the complete documentation index at: https://wb-21fd5541-docs-sandboxes-integrations-placement.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Hugging Face Diffusers

> Hugging Face Diffusers と W&B autolog を使用して、プロンプト、生成されたメディア、設定、パイプラインアーキテクチャをトラッキングします。

export const ColabLink = ({url}) => <a href={url} target="_blank" rel="noopener noreferrer" className="colab-link">
    <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
      <path d="M14.25.18l.9.2.73.26.59.3.45.32.34.34.25.34.16.33.1.3.04.26.02.2-.01.13V8.5l-.05.63-.13.55-.21.46-.26.38-.3.31-.33.25-.35.19-.35.14-.33.1-.3.07-.26.04-.21.02H8.77l-.69.05-.59.14-.5.22-.41.27-.33.32-.27.35-.2.36-.15.37-.1.35-.07.32-.04.27-.02.21v3.06H3.17l-.21-.03-.28-.07-.32-.12-.35-.18-.36-.26-.36-.36-.35-.46-.32-.59-.28-.73-.21-.88-.14-1.05-.05-1.23.06-1.22.16-1.04.24-.87.32-.71.36-.57.4-.44.42-.33.42-.24.4-.16.36-.1.32-.05.24-.01h.16l.06.01h8.16v-.83H6.18l-.01-2.75-.02-.37.05-.34.11-.31.17-.28.25-.26.31-.23.38-.2.44-.18.51-.15.58-.12.64-.1.71-.06.77-.04.84-.02 1.27.05zm-6.3 1.98l-.23.33-.08.41.08.41.23.34.33.22.41.09.41-.09.33-.22.23-.34.08-.41-.08-.41-.23-.33-.33-.22-.41-.09-.41.09zm13.09 3.95l.28.06.32.12.35.18.36.27.36.35.35.47.32.59.28.73.21.88.14 1.04.05 1.23-.06 1.23-.16 1.04-.24.86-.32.71-.36.57-.4.45-.42.33-.42.24-.4.16-.36.09-.32.05-.24.02-.16-.01h-8.22v.82h5.84l.01 2.76.02.36-.05.34-.11.31-.17.29-.25.25-.31.24-.38.2-.44.17-.51.15-.58.13-.64.09-.71.07-.77.04-.84.01-1.27-.04-1.07-.14-.9-.2-.73-.25-.59-.3-.45-.33-.34-.34-.25-.34-.16-.33-.1-.3-.04-.25-.02-.2.01-.13v-5.34l.05-.64.13-.54.21-.46.26-.38.3-.32.33-.24.35-.2.35-.14.33-.1.3-.06.26-.04.21-.02.13-.01h5.84l.69-.05.59-.14.5-.21.41-.28.33-.32.27-.35.2-.36.15-.36.1-.35.07-.32.04-.28.02-.21V6.07h2.09l.14.01.21.03zm-6.47 14.25l-.23.33-.08.41.08.41.23.33.33.23.41.08.41-.08.33-.23.23-.33.08-.41-.08-.41-.23-.33-.33-.23-.41-.08-.41.08z" />
    </svg>
    Colabで試す
  </a>;

<ColabLink url="https://colab.research.google.com/github/wandb/examples/blob/master/colabs/diffusers/lcm-diffusers.ipynb" />

[Hugging Face Diffusers](https://huggingface.co/docs/diffusers/index) は、画像やオーディオ、さらには分子の3D構造まで生成できる、最先端の事前学習済み拡散モデル向けの定番ライブラリです。W\&B インテグレーションを使うと、その使いやすさを損なうことなく、豊富で柔軟な実験管理、メディアの可視化、パイプラインアーキテクチャ、設定管理を、インタラクティブな一元管理ダッシュボードで利用できます。

<div id="next-level-logging-in-just-two-lines">
  ## たった2行で高度なロギング
</div>

たった2行のコードを追加するだけで、実験に関連するすべてのプロンプト、ネガティブプロンプト、生成されたメディア、設定をログできます。ロギングを開始するための2行のコードを以下に示します。

```python theme={null}
# autolog関数をimportする
from wandb.integration.diffusers import autolog

# パイプラインを呼び出す前にautologを呼び出す
autolog(init=dict(project="diffusers_logging"))
```

<Frame caption="実験結果がどのようにログされるかを示す例。">
  <img src="https://mintcdn.com/wb-21fd5541-docs-sandboxes-integrations-placement/F9fRIboixVPY5pzA/images/integrations/diffusers-autolog-4.gif?s=9581f2f8977bfa3490e28f2425414a64" alt="実験結果のログ記録" width="800" height="419" data-path="images/integrations/diffusers-autolog-4.gif" />
</Frame>

<div id="get-started">
  ## Get started
</div>

1. `diffusers`、`transformers`、`accelerate`、`wandb` をインストールします。

   * コマンドライン:

     ```shell theme={null}
     pip install --upgrade diffusers transformers accelerate wandb
     ```

   * ノートブック:

     ```bash theme={null}
     !pip install --upgrade diffusers transformers accelerate wandb
     ```

2. `autolog` を使用して W\&B Run を初期化し、[サポートされているすべてのパイプライン呼び出し](https://github.com/wandb/wandb/blob/main/wandb/integration/diffusers/autologger.py#L12-L72)の入力と出力を自動的にトラッキングします。

   `autolog()` 関数は `init` パラメーター付きで呼び出すことができ、このパラメーターには [`wandb.init()`](/ja/models/ref/python/functions/init) に必要なパラメーターを含む辞書を指定します。

   `autolog()` を呼び出すと、W\&B Run が初期化され、[サポートされているすべてのパイプライン呼び出し](https://github.com/wandb/wandb/blob/main/wandb/integration/diffusers/autologger.py#L12-L72)の入力と出力が自動的にトラッキングされます。

   * 各パイプライン呼び出しは、Workspace 内のそれぞれ専用の[表](/ja/models/tables/)にトラッキングされ、その呼び出しに関連付けられた設定は、その run の設定内にあるワークフローのリストに追加されます。
   * プロンプト、ネガティブプロンプト、生成されたメディアは [`wandb.Table`](/ja/models/tables/) にログされます。
   * seed やパイプラインアーキテクチャを含む、実験 に関連するその他すべての設定は、その run の config セクションに保存されます。
   * 各パイプライン呼び出しで生成されたメディアも、run 内の[メディアパネル](/ja/models/track/log/media/)にログされます。

   <Note>
     [サポートされているパイプライン呼び出しの一覧](https://github.com/wandb/wandb/blob/main/wandb/integration/diffusers/autologger.py#L12-L72)を確認できます。このインテグレーションの新機能をリクエストしたい場合や、関連する bug を報告したい場合は、[W\&B GitHub issues page](https://github.com/wandb/wandb/issues) で issue を作成してください。
   </Note>

<div id="examples">
  ## 例
</div>

<div id="autologging">
  ### オートロギング
</div>

以下は、autolog が実際にどのように動作するかを示す、簡単なエンドツーエンドの例です。

<Tabs>
  <Tab title="スクリプト">
    ```python theme={null}
    import torch
    from diffusers import DiffusionPipeline

    # autolog 関数をインポートする
    from wandb.integration.diffusers import autolog

    # パイプラインを呼び出す前に autolog を呼び出す
    autolog(init=dict(project="diffusers_logging"))

    # Diffusion パイプラインを初期化する
    pipeline = DiffusionPipeline.from_pretrained(
        "stabilityai/stable-diffusion-2-1", torch_dtype=torch.float16
    ).to("cuda")

    # プロンプト、ネガティブプロンプト、シードを定義する
    prompt = ["a photograph of an astronaut riding a horse", "a photograph of a dragon"]
    negative_prompt = ["ugly, deformed", "ugly, deformed"]
    generator = torch.Generator(device="cpu").manual_seed(10)

    # パイプラインを呼び出して画像を生成する
    images = pipeline(
        prompt,
        negative_prompt=negative_prompt,
        num_images_per_prompt=2,
        generator=generator,
    )
    ```
  </Tab>

  <Tab title="Notebook">
    ```python theme={null}
    import torch
    from diffusers import DiffusionPipeline

    import wandb

    # autolog 関数をインポートする
    from wandb.integration.diffusers import autolog

    run = wandb.init()

    # パイプラインを呼び出す前に autolog を呼び出す
    autolog(init=dict(project="diffusers_logging"))

    # Diffusion パイプラインを初期化する
    pipeline = DiffusionPipeline.from_pretrained(
        "stabilityai/stable-diffusion-2-1", torch_dtype=torch.float16
    ).to("cuda")

    # プロンプト、ネガティブプロンプト、シードを定義する
    prompt = ["a photograph of an astronaut riding a horse", "a photograph of a dragon"]
    negative_prompt = ["ugly, deformed", "ugly, deformed"]
    generator = torch.Generator(device="cpu").manual_seed(10)

    # パイプラインを呼び出して画像を生成する
    images = pipeline(
        prompt,
        negative_prompt=negative_prompt,
        num_images_per_prompt=2,
        generator=generator,
    )

    # 実験を終了する
    run.finish()
    ```
  </Tab>
</Tabs>

* 1 回の実験の結果:

  <Frame>
    <img src="https://mintcdn.com/wb-21fd5541-docs-sandboxes-integrations-placement/F9fRIboixVPY5pzA/images/integrations/diffusers-autolog-2.gif?s=0869b708d4b69db3088aee5f785526b4" alt="実験結果のログ" width="900" height="508" data-path="images/integrations/diffusers-autolog-2.gif" />
  </Frame>

* 複数の実験の結果:

  <Frame>
    <img src="https://mintcdn.com/wb-21fd5541-docs-sandboxes-integrations-placement/F9fRIboixVPY5pzA/images/integrations/diffusers-autolog-1.gif?s=b0cb88b6100f75a4b3d0df9e26cef0fb" alt="実験結果のログ" width="888" height="448" data-path="images/integrations/diffusers-autolog-1.gif" />
  </Frame>

* 実験の設定:

  <Frame>
    <img src="https://mintcdn.com/wb-21fd5541-docs-sandboxes-integrations-placement/F9fRIboixVPY5pzA/images/integrations/diffusers-autolog-3.gif?s=c87ec80eabc8cef8d5a40f41dc87e28f" alt="実験設定のログ" width="600" height="683" data-path="images/integrations/diffusers-autolog-3.gif" />
  </Frame>

<Note>
  IPython Notebook 環境でパイプラインの呼び出し後にコードを実行する場合は、[`wandb.Run.finish()`](/ja/models/ref/python/functions/finish) を明示的に呼び出す必要があります。Python スクリプトを実行する場合は不要です。
</Note>

<div id="tracking-multi-pipeline-workflows">
  ### 複数パイプラインのワークフローをトラッキングする
</div>

このセクションでは、典型的な [Stable Diffusion XL + Refiner](https://huggingface.co/docs/diffusers/using-diffusers/sdxl#base-to-refiner-model) ワークフローを例に、autolog を示します。このワークフローでは、[`StableDiffusionXLPipeline`](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl) によって生成された latent を、対応する Refiner でさらに精緻化します。

<Tabs>
  <Tab title="Python スクリプト">
    ```python theme={null}
    import torch
    from diffusers import StableDiffusionXLImg2ImgPipeline, StableDiffusionXLPipeline
    from wandb.integration.diffusers import autolog

    # SDXLベースパイプラインを初期化する
    base_pipeline = StableDiffusionXLPipeline.from_pretrained(
        "stabilityai/stable-diffusion-xl-base-1.0",
        torch_dtype=torch.float16,
        variant="fp16",
        use_safetensors=True,
    )
    base_pipeline.enable_model_cpu_offload()

    # SDXLリファイナーパイプラインを初期化する
    refiner_pipeline = StableDiffusionXLImg2ImgPipeline.from_pretrained(
        "stabilityai/stable-diffusion-xl-refiner-1.0",
        text_encoder_2=base_pipeline.text_encoder_2,
        vae=base_pipeline.vae,
        torch_dtype=torch.float16,
        use_safetensors=True,
        variant="fp16",
    )
    refiner_pipeline.enable_model_cpu_offload()

    prompt = "a photo of an astronaut riding a horse on mars"
    negative_prompt = "static, frame, painting, illustration, sd character, low quality, low resolution, greyscale, monochrome, nose, cropped, lowres, jpeg artifacts, deformed iris, deformed pupils, bad eyes, semi-realistic worst quality, bad lips, deformed mouth, deformed face, deformed fingers, deformed toes standing still, posing"

    # ランダム性を制御して実験を再現可能にする。
    # シードはWandBに自動的にログされる。
    seed = 42
    generator_base = torch.Generator(device="cuda").manual_seed(seed)
    generator_refiner = torch.Generator(device="cuda").manual_seed(seed)

    # DiffusersのWandB Autologを呼び出す。これにより、プロンプト、生成画像、
    # パイプラインアーキテクチャ、および関連するすべての実験設定がW&Bに自動的にログされ、
    # 画像生成実験の再現・共有・分析が容易になる。
    autolog(init=dict(project="sdxl"))

    # ベースパイプラインを呼び出して潜在変数を生成する
    image = base_pipeline(
        prompt=prompt,
        negative_prompt=negative_prompt,
        output_type="latent",
        generator=generator_base,
    ).images[0]

    # リファイナーパイプラインを呼び出して精緻化された画像を生成する
    image = refiner_pipeline(
        prompt=prompt,
        negative_prompt=negative_prompt,
        image=image[None, :],
        generator=generator_refiner,
    ).images[0]
    ```
  </Tab>

  <Tab title="ノートブック">
    ```python theme={null}
    import torch
    from diffusers import StableDiffusionXLImg2ImgPipeline, StableDiffusionXLPipeline

    import wandb
    from wandb.integration.diffusers import autolog

    run = wandb.init()

    # SDXLベースパイプラインを初期化する
    base_pipeline = StableDiffusionXLPipeline.from_pretrained(
        "stabilityai/stable-diffusion-xl-base-1.0",
        torch_dtype=torch.float16,
        variant="fp16",
        use_safetensors=True,
    )
    base_pipeline.enable_model_cpu_offload()

    # SDXLリファイナーパイプラインを初期化する
    refiner_pipeline = StableDiffusionXLImg2ImgPipeline.from_pretrained(
        "stabilityai/stable-diffusion-xl-refiner-1.0",
        text_encoder_2=base_pipeline.text_encoder_2,
        vae=base_pipeline.vae,
        torch_dtype=torch.float16,
        use_safetensors=True,
        variant="fp16",
    )
    refiner_pipeline.enable_model_cpu_offload()

    prompt = "a photo of an astronaut riding a horse on mars"
    negative_prompt = "static, frame, painting, illustration, sd character, low quality, low resolution, greyscale, monochrome, nose, cropped, lowres, jpeg artifacts, deformed iris, deformed pupils, bad eyes, semi-realistic worst quality, bad lips, deformed mouth, deformed face, deformed fingers, deformed toes standing still, posing"

    # ランダム性を制御して実験を再現可能にする。
    # シードはWandBに自動的にログされる。
    seed = 42
    generator_base = torch.Generator(device="cuda").manual_seed(seed)
    generator_refiner = torch.Generator(device="cuda").manual_seed(seed)

    # DiffusersのWandB Autologを呼び出す。これにより、プロンプト、生成画像、
    # パイプラインアーキテクチャ、および関連するすべての実験設定がW&Bに自動的にログされ、
    # 画像生成実験の再現、共有、分析が容易になる。
    autolog(init=dict(project="sdxl"))

    # ベースパイプラインを呼び出して潜在変数を生成する
    image = base_pipeline(
        prompt=prompt,
        negative_prompt=negative_prompt,
        output_type="latent",
        generator=generator_base,
    ).images[0]

    # リファイナーパイプラインを呼び出して精製画像を生成する
    image = refiner_pipeline(
        prompt=prompt,
        negative_prompt=negative_prompt,
        image=image[None, :],
        generator=generator_refiner,
    ).images[0]

    # 実験を終了する
    run.finish()
    ```
  </Tab>
</Tabs>

* Stable Diffusion XL + Refiner の実験例:
  <Frame>
    <img src="https://mintcdn.com/wb-21fd5541-docs-sandboxes-integrations-placement/F9fRIboixVPY5pzA/images/integrations/diffusers-autolog-6.gif?s=54f229a8a9ce5bb47044396fb57d0473" alt="Stable Diffusion XL の実験管理" width="800" height="418" data-path="images/integrations/diffusers-autolog-6.gif" />
  </Frame>

<div id="more-resources">
  ## 参考資料
</div>

* [Stable Diffusion向けプロンプトエンジニアリングガイド](https://wandb.ai/geekyrakshit/diffusers-prompt-engineering/reports/A-Guide-to-Prompt-Engineering-for-Stable-Diffusion--Vmlldzo1NzY4NzQ3)
* [PIXART-α: テキストから画像を生成するためのDiffusion Transformerモデル](https://wandb.ai/geekyrakshit/pixart-alpha/reports/PIXART-A-Diffusion-Transformer-Model-for-Text-to-Image-Generation--Vmlldzo2MTE1NzM3)
