# InstructPix2Pix

  

[InstructPix2Pix: Learning to Follow Image Editing Instructions](https://huggingface.co/papers/2211.09800)は、Tim Brooks、Aleksander Holynski、Alexei A. Efros によるものです。

論文の抄録は以下の通りです：

*人間からの指示に基づいて画像を編集する手法を提案します。入力画像と、モデルに何をすべきかを伝える書面による指示が与えられた場合、当社のモデルはこれらの指示に従って画像を編集します。この問題の学習データを得るために、2つの大規模事前学習モデル、すなわち言語モデル（GPT-3）とテキストから画像を生成するモデル（Stable Diffusion）の知識を組み合わせ、画像編集の例からなる大規模なデータセットを生成しました。条件付き拡散モデルであるInstructPix2Pixは、この生成データで学習され、推論時には実際の画像やユーザーが書いた指示にも一般化します。編集をフォワードパスで実行し、例ごとのファインチューニングやインバージョンを必要としないため、当社のモデルは数秒で画像を編集できます。多様な入力画像と書面による指示に対して、説得力のある編集結果を示します。*

InstructPix2Pixに関する追加情報は、[論文](https://huggingface.co/papers/2211.09800)、[元のコードベース](https://github.com/timothybrooks/instruct-pix2pix)、および[デモ](https://huggingface.co/spaces/timbrooks/instruct-pix2pix)で試すことができます。

> [!TIP]
> スケジューラーのトレードオフ、すなわち速度と品質のバランスをどのように探求するかを学ぶには、[ガイド](../../using-diffusers/schedulers)を必ずご確認ください。また、同じコンポーネントを複数のパイプラインに効率的に読み込む方法については、[パイプライン間でコンポーネントを再利用する](../../using-diffusers/loading#reusing-models-in-multiple-pipelines)セクションを参照してください。

## StableDiffusionInstructPix2PixPipeline[[diffusers.StableDiffusionInstructPix2PixPipeline]]

#### diffusers.StableDiffusionInstructPix2PixPipeline[[diffusers.StableDiffusionInstructPix2PixPipeline]]

```python
diffusers.StableDiffusionInstructPix2PixPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet2DConditionModel, scheduler: KarrasDiffusionSchedulers, safety_checker: StableDiffusionSafetyChecker, feature_extractor: CLIPImageProcessorPil, image_encoder: transformers.models.clip.modeling_clip.CLIPVisionModelWithProjection | None = None, requires_safety_checker: bool = True)
```

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py#L83)

**パラメータ:**

vae ([AutoencoderKL](/docs/diffusers/v0.43.0/ja/api/models/autoencoderkl#diffusers.AutoencoderKL)) : 画像を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ（VAE）モデル。

text_encoder ([CLIPTextModel](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPTextModel)) : 凍結されたテキストエンコーダー ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14))。

tokenizer ([CLIPTokenizer](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPTokenizer)) : テキストをトークン化するための`CLIPTokenizer`。

unet ([UNet2DConditionModel](/docs/diffusers/v0.43.0/ja/api/models/unet2d-cond#diffusers.UNet2DConditionModel)) : エンコードされた画像の潜在変数をノイズ除去するための `UNet2DConditionModel`。

scheduler ([SchedulerMixin](/docs/diffusers/v0.43.0/ja/api/schedulers/overview#diffusers.SchedulerMixin)) : `unet` と組み合わせて、エンコードされた画像の潜在変数をデノイズするために使用するスケジューラ。[DDIMScheduler](/docs/diffusers/v0.43.0/ja/api/schedulers/ddim#diffusers.DDIMScheduler)、[LMSDiscreteScheduler](/docs/diffusers/v0.43.0/ja/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler)、または [PNDMScheduler](/docs/diffusers/v0.43.0/ja/api/schedulers/pndm#diffusers.PNDMScheduler) のいずれかです。

safety_checker (`StableDiffusionSafetyChecker`) : 生成された画像が攻撃的または有害とみなされる可能性を推定する分類モジュールです。モデルの潜在的な害に関する詳細については、[モデルカード](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5)を参照してください。

feature_extractor ([CLIPImageProcessor](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPImageProcessor)) : 生成された画像から特徴量を抽出するための`CLIPImageProcessor`。`safety_checker`の入力として使用されます。

テキスト指示に従ってピクセルレベルの画像編集を行うためのPipeline（Stable Diffusionベース）。

このモデルは [DiffusionPipeline](/docs/diffusers/v0.43.0/ja/api/pipelines/overview#diffusers.DiffusionPipeline) を継承しています。すべてのパイプラインに実装されている汎用的なメソッド（ダウンロード、保存、特定のデバイスでの実行など）については、スーパークラスのドキュメントを参照してください。

パイプラインは、以下の読み込みメソッドも継承します:
- テキストインバージョンの埋め込みを読み込むための[load_textual_inversion()](/docs/diffusers/v0.43.0/ja/api/loaders/textual_inversion#diffusers.loaders.TextualInversionLoaderMixin.load_textual_inversion)
- LoRA重みの読み込みに[load_lora_weights()](/docs/diffusers/v0.43.0/ja/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights)
- LoRA重みの保存には[save_lora_weights()](/docs/diffusers/v0.43.0/ja/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.save_lora_weights)を使用します
- IP Adapterの読み込みに[load_ip_adapter()](/docs/diffusers/v0.43.0/ja/api/loaders/ip_adapter#diffusers.loaders.IPAdapterMixin.load_ip_adapter)

#### __call__[[diffusers.StableDiffusionInstructPix2PixPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, num_inference_steps: int = 100, guidance_scale: float = 7.5, image_guidance_scale: float = 1.5, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, ip_adapter_image_embeds: list[torch.Tensor] | None = None, output_type: str | None = 'pil', return_dict: bool = True, callback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], cross_attention_kwargs: dict[str, typing.Any] | None = None, **kwargs)
```

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py#L172)

**パラメータ:**

prompt (`str` または `list[str]`、*省略可能*) : 画像生成をガイドするためのプロンプトです。定義されていない場合は、`prompt_embeds` を渡す必要があります。

image (`torch.Tensor` `np.ndarray`、`PIL.Image.Image`、`list[torch.Tensor]`、`list[PIL.Image.Image]`、または `list[np.ndarray]`) : `prompt` に従って再描画する画像バッチを表す `Image` またはテンソル。画像の潜在変数も `image` として受け取れますが、潜在変数を直接渡す場合は再度エンコードされません。

num_inference_steps (`int`、*optional*、デフォルト値は 100) : デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。

guidance_scale (`float`、*任意*、デフォルト値は 7.5) : 高い guidance scale の値は、画像の品質が低下する代わりに、テキストの `prompt` と密接に関連した画像を生成するようモデルを促します。`guidance_scale > 1` の場合、guidance scale が有効になります。

image_guidance_scale (`float`、*任意*、デフォルト値は 1.5) : 生成される画像を初期の `image` に近づけます。`image_guidance_scale > 1` を設定することで、画像ガイダンススケールが有効になります。画像ガイダンススケールを高くすると、ソースの `image` と密接に関連する生成画像が得られやすくなりますが、通常は画像品質の低下を伴います。このパイプラインでは、少なくとも `1` 以上の値が必要です。

negative_prompt (`str` または `list[str]`、*省略可能*) : 画像生成に含めるべきでない内容を指示するためのプロンプトまたはプロンプトのリストです。定義されていない場合、代わりに `negative_prompt_embeds` を渡す必要があります。ガイダンスを使用していない場合（`guidance_scale < 1`）は無視されます。

num_images_per_prompt (`int`、*任意*、デフォルトは 1) : プロンプトごとに生成する画像の数。

eta (`float`、*任意*、デフォルト値は 0.0) : [DDIM](https://huggingface.co/papers/2010.02502)論文のパラメータ eta (η) に対応します。[DDIMScheduler](/docs/diffusers/v0.43.0/ja/api/schedulers/ddim#diffusers.DDIMScheduler)でのみ適用され、他のスケジューラーでは無視されます。

generator (`torch.Generator`, *任意*) : 生成を決定論的にするための [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html)。

latents (`torch.Tensor`, *任意*) : 画像生成の入力として使用される、ガウス分布からサンプリングされた事前生成されたノイジー・ラテンツ。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダム`generator`を使用してサンプリングを行い、ラテンツのテンソルが生成されます。

prompt_embeds (`torch.Tensor`, *任意*) : 事前に生成されたテキスト埋め込み。テキスト入力（プロンプトの重み付け）を簡単に調整するために使用できます。指定されない場合、`prompt` 入力引数からテキスト埋め込みが生成されます。

negative_prompt_embeds (`torch.Tensor`, *任意*) : 事前に生成されたネガティブなテキスト埋め込み。テキスト入力（プロンプトの重み付け）を簡単に調整するために使用できます。指定されない場合、`negative_prompt_embeds` は `negative_prompt` 入力引数から生成されます。

ip_adapter_image : (`PipelineImageInput`、*任意*): IP Adapter で使用する任意の画像入力。

ip_adapter_image_embeds (`list[torch.Tensor]`, *任意*) : IP-Adapter 用の事前生成された画像埋め込みです。IP-Adapter の数と同じ長さのリストである必要があります。各要素は、`(batch_size, num_images, emb_dim)` の形状を持つテンソルである必要があります。`do_classifier_free_guidance` が `True` に設定されている場合、負の画像埋め込みを含む必要があります。指定されない場合、`ip_adapter_image` 入力引数から埋め込みが計算されます。

output_type (`str`、*任意*、デフォルトは`"pil"`) : 生成された画像の出力形式。`PIL.Image`または`np.array`から選択します。

return_dict (`bool`、*任意*、デフォルトは`True`) : プレーンなタプルではなく、[StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/ja/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput)を返すかどうか。

callback_on_step_end (`Callable`、`PipelineCallback`、`MultiPipelineCallbacks`、*任意*) : 推論中の各デノイジングステップの終了時に呼び出される関数、または `PipelineCallback` または `MultiPipelineCallbacks` のサブクラスです。以下の引数を持ちます: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`。`callback_kwargs` には、`callback_on_step_end_tensor_inputs` で指定されたすべてのテンソルのリストが含まれます。

callback_on_step_end_tensor_inputs (`list`, *任意*) : `callback_on_step_end` 関数へのテンソル入力のリストです。リストで指定されたテンソルは、`callback_kwargs` 引数として渡されます。パイプラインクラスの `._callback_tensor_inputs` 属性に列挙された変数のみを、リストに含めることができます。

cross_attention_kwargs (`dict`, *任意*) : 指定された場合、[`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) で定義されている `AttentionProcessor` に渡される kwargs の辞書です。

**戻り値:** [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/ja/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) または `tuple`

If `return_dict` is `True`, [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/ja/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) is returned, otherwise a `tuple` is returned where the first element is a list with the generated images and the second element is a list of `bool`s indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.

生成用の pipeline への呼び出し関数。

例:

```py
>>> import PIL
>>> import requests
>>> import torch
>>> from io import BytesIO

>>> from diffusers import StableDiffusionInstructPix2PixPipeline

>>> def download_image(url):
...     response = requests.get(url)
...     return PIL.Image.open(BytesIO(response.content)).convert("RGB")

>>> img_url = "https://huggingface.co/datasets/diffusers/diffusers-images-docs/resolve/main/mountain.png"

>>> image = download_image(img_url).resize((512, 512))

>>> pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained(
...     "timbrooks/instruct-pix2pix", torch_dtype=torch.float16
... )
>>> pipe = pipe.to("cuda")

>>> prompt = "make the mountains snowy"
>>> image = pipe(prompt=prompt, image=image).images[0]
```

#### load_textual_inversion[[diffusers.StableDiffusionInstructPix2PixPipeline.load_textual_inversion]]

```python
load_textual_inversion(pretrained_model_name_or_path: str | list[str] | dict[str, torch.Tensor] | list[dict[str, torch.Tensor]], token: str | list[str] | None = None, tokenizer: 'PreTrainedTokenizer' | None = None, text_encoder: 'PreTrainedModel' | None = None, **kwargs)
```

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/loaders/textual_inversion.py#L271)

**パラメータ:**

pretrained_model_name_or_path (`str` または `os.PathLike` または `list[str or os.PathLike]` または `Dict` または `list[Dict]`) : 以下のいずれか、またはそれらのリストを指定できます。 - Hub にホストされている事前学習済みモデルの *model id*（例: `sd-concepts-library/low-poly-hd-logos-icons`）を表す文字列。 - テキストインバージョンの重みを含む *ディレクトリ* へのパス（例: `./my_text_inversion_directory/`）。 - テキストインバージョンの重みを含む *ファイル* へのパス（例: `./my_text_inversions.pt`）。 - [torch state dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict)。

token (`str` または `list[str]`、*省略可能*) : テキスト反転の重みに使用するトークンを上書きします。`pretrained_model_name_or_path` がリストの場合、`token` も同じ長さのリストである必要があります。

text_encoder ([CLIPTextModel](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPTextModel)、*任意*) : 凍結されたテキストエンコーダー ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14))。指定しない場合、関数は self.tokenizer を使用します。

tokenizer ([CLIPTokenizer](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPTokenizer)、*任意*) : テキストをトークン化するための`CLIPTokenizer`。指定しない場合、関数はself.tokenizerを使用します。

weight_name (`str`, *任意*) : カスタム重みファイルの名前。次の場合に使用します。 - 保存されたテキストインバージョンファイルが🤗 Diffusers形式であるが、`text_inv.bin`のような特定の重み名で保存されている場合。 - 保存されたテキストインバージョンファイルがAutomatic1111形式である場合。

cache_dir (`str | os.PathLike`、*任意*) : 標準のキャッシュを使用しない場合、ダウンロードした事前学習済みモデルの構成がキャッシュされるディレクトリのパス。

force_download (`bool`, *任意*, デフォルトは `False`) : モデルの重みと設定ファイルの(再)ダウンロードを強制するかどうか。キャッシュされたバージョンが存在する場合でも、それを上書きします。

proxies (`dict[str, str]`、*省略可*) : プロトコルまたはエンドポイントごとに使用するプロキシサーバーの辞書です。例えば、`{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}` のように指定します。これらのプロキシは、各リクエストで使用されます。

local_files_only (`bool`、*任意*、デフォルトは`False`) : ローカルのモデルの重みと設定ファイルのみを読み込むかどうかを指定します。`True`に設定すると、モデルは Hub からダウンロードされません。

hf_token (`str` または *bool*、*省略可能*) : リモートファイルの HTTP ベアラ認証に使用するトークン。`True` の場合、`diffusers-cli login` で生成されたトークン（`~/.huggingface` に保存）が使用されます。

revision (`str`、*任意*、デフォルトは`"main"`) : 使用する特定のモデルバージョンです。ブランチ名、タグ名、コミット ID、または Git で許可されている任意の識別子を使用できます。

subfolder (`str`、*任意*、デフォルトは `""`) : Hub またはローカル上のより大きなモデルリポジトリ内での、モデルファイルのサブフォルダの場所。

mirror (`str`, *任意*) : 中国でモデルをダウンロードする場合、アクセシビリティの問題を解決するためのミラーソースを指定します。ソースの鮮度や安全性を保証するものではなく、詳細についてはミラーサイトをご参照ください。

[StableDiffusionPipeline](/docs/diffusers/v0.43.0/ja/api/pipelines/stable_diffusion/text2img#diffusers.StableDiffusionPipeline)のテキストエンコーダーにTextual Inversionの埋め込みを読み込みます（🤗 Diffusers形式とAutomatic1111形式の両方をサポートしています）。

例:

🤗 Diffusers形式でTextual Inversion埋め込みベクトルを読み込むには:

```py
from diffusers import StableDiffusionPipeline
import torch

model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")

pipe.load_textual_inversion("sd-concepts-library/cat-toy")

prompt = "A <cat-toy> backpack"

image = pipe(prompt, num_inference_steps=50).images[0]
image.save("cat-backpack.png")
```

Automatic1111形式のTextual Inversion埋め込みベクトルを読み込むには、まずベクトルをダウンロードしてください（[civitAI](https://civitai.com/models/3036?modelVersionId=9857)などから）。その後、ベクトルを読み込みます。

ローカルで:

```py
from diffusers import StableDiffusionPipeline
import torch

model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")

pipe.load_textual_inversion("./charturnerv2.pt", token="charturnerv2")

prompt = "charturnerv2, multiple views of the same character in the same outfit, a character turnaround of a woman wearing a black jacket and red shirt, best quality, intricate details."

image = pipe(prompt, num_inference_steps=50).images[0]
image.save("character.png")
```

#### load_lora_weights[[diffusers.StableDiffusionInstructPix2PixPipeline.load_lora_weights]]

```python
load_lora_weights(pretrained_model_name_or_path_or_dict: str | dict[str, torch.Tensor], adapter_name: str | None = None, hotswap: bool = False, **kwargs)
```

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/loaders/lora_pipeline.py#L148)

**パラメータ:**

pretrained_model_name_or_path_or_dict (`str` または `os.PathLike` または `dict`) : [lora_state_dict()](/docs/diffusers/v0.43.0/ja/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.lora_state_dict) を参照してください。

adapter_name (`str`, *省略可*) : 読み込まれたアダプターモデルを参照するために使用するアダプター名。指定しない場合、読み込まれるアダプターの総数を i として `default_{i}` が使用されます。

low_cpu_mem_usage (`bool`, *省略可*) : ランダムな重みの初期化を行わず、事前学習済み LoRA 重みのみを読み込むことで、モデルの読み込みを高速化します。

hotswap (`bool`, *任意*) : デフォルトは `False` です。既存の (LoRA) アダプターを、新しく読み込まれたアダプターでその場で置き換えるかどうかを指定します。つまり、追加のアダプターを読み込むのではなく、既存のアダプターの重みを新しいアダプターの重みで置き換えます。これにより、より高速かつメモリ効率の高い処理が可能になります。ただし、ホットスワップの主な利点は、モデルが torch.compile でコンパイルされている場合、新しいアダプターを読み込んでもモデルの再コンパイルが不要になる点です。ホットスワップを使用する場合は、渡す `adapter_name` は、すでに読み込まれているアダプターの名前である必要があります。 新しいアダプターと古いアダプターでランクと/または LoRA alpha (すなわちスケーリング) が異なる場合、アダプターを読み込む前に追加のメソッドを呼び出す必要があります: ```py pipeline = ...  # load diffusers pipeline max_rank = ...  # the highest rank among all LoRAs that you want to load # call *before* compiling and loading the LoRA adapter pipeline.enable_lora_hotswap(target_rank=max_rank) pipeline.load_lora_weights(file_name) # optionally compile the model now ``` テキストエンコーダーのアダプターのホットスワップは、まだサポートされていません。この技術にはいくつかの制限があり、以下にドキュメント化されています: https://huggingface.co/docs/peft/main/en/package_reference/hotswap

kwargs (`dict`、*任意*) : [lora_state_dict()](/docs/diffusers/v0.43.0/ja/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.lora_state_dict)を参照してください。

`pretrained_model_name_or_path_or_dict` で指定された LoRA の重みを `self.unet` および `self.text_encoder` に読み込みます。

すべてのkwargsは`self.lora_state_dict`に転送されます。

ステートディクトの読み込み方法の詳細については、[lora_state_dict()](/docs/diffusers/v0.43.0/ja/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.lora_state_dict)を参照してください。

`self.unet` にステートディクトがどのように読み込まれるかについては、[load_lora_into_unet()](/docs/diffusers/v0.43.0/ja/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_into_unet) を参照してください。

`self.text_encoder` に state dict がどのように読み込まれるかについては、[load_lora_into_text_encoder()](/docs/diffusers/v0.43.0/ja/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_into_text_encoder) を参照してください。

#### save_lora_weights[[diffusers.StableDiffusionInstructPix2PixPipeline.save_lora_weights]]

```python
save_lora_weights(save_directory: str | os.PathLike, unet_lora_layers: dict[str, typing.Union[torch.nn.Module, torch.Tensor]] = None, text_encoder_lora_layers: dict[str, torch.nn.Module] = None, is_main_process: bool = True, weight_name: str = None, save_function: typing.Callable = None, safe_serialization: bool = True, unet_lora_adapter_metadata = None, text_encoder_lora_adapter_metadata = None)
```

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/loaders/lora_pipeline.py#L466)

**パラメータ:**

save_directory (`str` または `os.PathLike`) : LoRA パラメータを保存するディレクトリ。存在しない場合は作成されます。

unet_lora_layers (`dict[str, torch.nn.Module]` または `dict[str, torch.Tensor]`) : `unet` に対応する LoRA レイヤーの state dict。

text_encoder_lora_layers (`dict[str, torch.nn.Module]` または `dict[str, torch.Tensor]`) : `text_encoder` に対応する LoRA レイヤーの state dict。🤗 Transformers から取得されるため、テキストエンコーダーの LoRA state dict を明示的に渡す必要があります。

is_main_process (`bool`、*任意*、デフォルトは`True`) : この関数を呼び出したプロセスがメインプロセスかどうかを示します。分散学習時に、すべてのプロセスでこの関数を呼び出す必要がある場合に便利です。この場合、競合状態を避けるために、メインプロセスでのみ`is_main_process=True`を設定してください。

save_function (`Callable`) : 状態辞書を保存するために使用する関数です。分散学習時に `torch.save` を別のメソッドに置き換える必要がある場合に便利です。環境変数 `DIFFUSERS_SAVE_MODE` で設定できます。

safe_serialization (`bool`、*任意*、デフォルトは`True`) : モデルを`safetensors`で保存するか、`pickle`を用いた従来の PyTorch の方法で保存するかどうかを指定します。

unet_lora_adapter_metadata : state dict と一緒にシリアライズされる unet に関連付けられた LoRA アダプターのメタデータ。

text_encoder_lora_adapter_metadata : state dict と一緒にシリアライズされる、テキストエンコーダーに関連付けられた LoRA アダプターのメタデータ。

UNetおよびテキストエンコーダーに対応するLoRAパラメータを保存します。

## StableDiffusionXLInstructPix2PixPipeline[[diffusers.StableDiffusionXLInstructPix2PixPipeline]]

#### diffusers.StableDiffusionXLInstructPix2PixPipeline[[diffusers.StableDiffusionXLInstructPix2PixPipeline]]

```python
diffusers.StableDiffusionXLInstructPix2PixPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, text_encoder_2: CLIPTextModelWithProjection, tokenizer: CLIPTokenizer, tokenizer_2: CLIPTokenizer, unet: UNet2DConditionModel, scheduler: KarrasDiffusionSchedulers, force_zeros_for_empty_prompt: bool = True, add_watermarker: bool | None = None, is_cosxl_edit: bool | None = False)
```

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py#L113)

**パラメータ:**

vae ([AutoencoderKL](/docs/diffusers/v0.43.0/ja/api/models/autoencoderkl#diffusers.AutoencoderKL)) : 画像を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ（VAE）モデル。

text_encoder (`CLIPTextModel`) : 凍結されたテキストエンコーダー。Stable Diffusion XL は [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel) のテキスト部分、具体的には [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) バリアントを使用します。

text_encoder_2 (` CLIPTextModelWithProjection`) : 2番目の凍結されたテキストエンコーダー。Stable Diffusion XL は [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection) のテキストおよびプール部分を使用しており、具体的には [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k) バリアントを使用しています。

tokenizer (`CLIPTokenizer`) : クラス [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer) の Tokenizer。

tokenizer_2 (`CLIPTokenizer`) : クラス [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer) の2番目の Tokenizer。

unet ([UNet2DConditionModel](/docs/diffusers/v0.43.0/ja/api/models/unet2d-cond#diffusers.UNet2DConditionModel)) : エンコードされた画像の潜在変数をノイズ除去するための条件付き U-Net アーキテクチャ。

scheduler ([SchedulerMixin](/docs/diffusers/v0.43.0/ja/api/schedulers/overview#diffusers.SchedulerMixin)) : `unet` と組み合わせて、エンコードされた画像の潜在変数をデノイズするために使用するスケジューラ。[DDIMScheduler](/docs/diffusers/v0.43.0/ja/api/schedulers/ddim#diffusers.DDIMScheduler)、[LMSDiscreteScheduler](/docs/diffusers/v0.43.0/ja/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler)、または [PNDMScheduler](/docs/diffusers/v0.43.0/ja/api/schedulers/pndm#diffusers.PNDMScheduler) のいずれかです。

requires_aesthetics_score (`bool`、*任意*、デフォルトは`"False"`) : 推論時に`unet`にaesthetic_score条件を渡す必要があるかどうかを示します。`stabilityai/stable-diffusion-xl-refiner-1-0`の設定も参照してください。

force_zeros_for_empty_prompt (`bool`、*任意*、デフォルトは`"True"`) : 負のプロンプト埋め込みを常に0に設定するかどうか。`stabilityai/stable-diffusion-xl-base-1-0`の設定も参照してください。

add_watermarker (`bool`, *任意*) : 出力画像にウォーターマークを付与するために[invisible_watermark ライブラリ](https://github.com/ShieldMnt/invisible-watermark/)を使用するかどうかを指定します。未定義の場合、パッケージがインストールされていればデフォルトで True となり、インストールされていなければウォーターマーカーは使用されません。

is_cosxl_edit (`bool`, *任意*) : 設定すると、画像の潜在変数がスケーリングされます。

テキスト指示に従ってピクセルレベルの画像編集を行うPipeline。Stable Diffusion XLをベースとしています。

このモデルは [DiffusionPipeline](/docs/diffusers/v0.43.0/ja/api/pipelines/overview#diffusers.DiffusionPipeline) を継承しています。ライブラリがすべてのパイプラインに対して実装している汎用的なメソッド（ダウンロードや保存、特定のデバイスでの実行など）については、スーパークラスのドキュメントを参照してください。

パイプラインは、以下の読み込みメソッドも継承します:
- テキストインバージョンの埋め込みを読み込むための[load_textual_inversion()](/docs/diffusers/v0.43.0/ja/api/loaders/textual_inversion#diffusers.loaders.TextualInversionLoaderMixin.load_textual_inversion)
- `.ckpt`ファイルを読み込むための[from_single_file()](/docs/diffusers/v0.43.0/ja/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file)
- LoRA重みの読み込みに[load_lora_weights()](/docs/diffusers/v0.43.0/ja/api/loaders/lora#diffusers.loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights)
- LoRA重みの保存には[save_lora_weights()](/docs/diffusers/v0.43.0/ja/api/loaders/lora#diffusers.loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights)を使用します

#### __call__[[diffusers.StableDiffusionXLInstructPix2PixPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, prompt_2: str | list[str] | None = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, height: int | None = None, width: int | None = None, num_inference_steps: int = 100, denoising_end: float | None = None, guidance_scale: float = 5.0, image_guidance_scale: float = 1.5, negative_prompt: str | list[str] | None = None, negative_prompt_2: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, output_type: str | None = 'pil', return_dict: bool = True, callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None, callback_steps: int = 1, cross_attention_kwargs: dict[str, typing.Any] | None = None, guidance_rescale: float = 0.0, original_size: tuple[int, int] = None, crops_coords_top_left: tuple[int, int] = (0, 0), target_size: tuple[int, int] = None)
```

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py#L595)

**パラメータ:**

prompt (`str` または `list[str]`、*省略可*) : 画像生成をガイドするためのプロンプトです。未定義の場合、代わりに `prompt_embeds` を渡す必要があります。

prompt_2 (`str` または `list[str]`、*省略可能*) : `tokenizer_2` および `text_encoder_2` に送信するプロンプトです。未定義の場合、両方のテキストエンコーダーで `prompt` が使用されます。

image (`torch.Tensor` または `PIL.Image.Image` または `np.ndarray` または `list[torch.Tensor]` または `list[PIL.Image.Image]` または `list[np.ndarray]`) : パイプラインで処理する画像です。

height (`int`、*任意*、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) : 生成される画像のピクセル単位の縦幅。

width (`int`、*任意*、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) : 生成される画像の幅（ピクセル単位）。

num_inference_steps (`int`、*任意*、デフォルト値は 50) : デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。

denoising_end (`float`, *任意*) : 指定すると、デノイジング全体のどの割合（0.0 から 1.0 の間）で処理を意図的に早期終了させるかを決定します。その結果、スケジューラによって選択された離散タイムステップによって決定されるように、返されるサンプルには依然としてかなりの量のノイズが残ります。[**画像出力の洗練**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output) に詳述されているように、このパラメータは、このパイプラインが「Mixture of Denoisers」マルチパイプライン構成の一部を形成する場合に、理想的には利用されるべきです。

guidance_scale (`float`、*任意*、デフォルト値は 5.0) : [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598)で定義されているガイダンススケールです。`guidance_scale` は、[Imagen Paper](https://huggingface.co/papers/2205.11487)の式 2 の `w` として定義されています。`guidance_scale > 1` を設定することで、ガイダンススケールが有効になります。ガイダンススケールを高くすると、`prompt` のテキストと密接に関連した画像の生成が促されますが、通常は画像の品質が低下する傾向があります。

image_guidance_scale (`float`、*任意*、デフォルト値は 1.5) : 生成される画像を初期画像 `image` に近づけるための画像ガイダンススケールです。`image_guidance_scale > 1` を設定することで、画像ガイダンススケールが有効になります。画像ガイダンススケールを高くすると、ソース画像 `image` と密接に関連した画像の生成が促されますが、通常は画像品質の低下を伴います。このパイプラインでは、少なくとも `1` 以上の値が必要です。

negative_prompt (`str` または `list[str]`、*省略可能*) : 画像生成をガイドしないプロンプトです。定義されていない場合、代わりに `negative_prompt_embeds` を渡す必要があります。ガイドを使用していない場合は無視されます（`guidance_scale` が `1` 未満の場合は無視されます）。

negative_prompt_2 (`str` または `list[str]`、*省略可能*) : `tokenizer_2` および `text_encoder_2` に送信する、画像生成を誘導しないためのプロンプトです。定義されていない場合、`negative_prompt` が両方のテキストエンコーダーで使用されます。

num_images_per_prompt (`int`、*任意*、デフォルトは 1) : プロンプトごとに生成する画像の数。

eta (`float`、*任意*、デフォルト値は 0.0) : DDIM 論文におけるパラメータ eta (η) に相当します: https://huggingface.co/papers/2010.02502。[schedulers.DDIMScheduler](/docs/diffusers/v0.43.0/ja/api/schedulers/ddim#diffusers.DDIMScheduler) にのみ適用され、それ以外のスケジューラーでは無視されます。

generator (`torch.Generator` または `list[torch.Generator]`、*任意*) : 生成を決定論的にするための [torch ジェネレーター](https://pytorch.org/docs/stable/generated/torch.Generator.html) 1 つまたはそのリスト。

latents (`torch.Tensor`, *任意*) : イメージ生成の入力として使用される、ガウス分布からサンプリングされた事前生成されたノイジー・ラテンツ。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダムな`generator`を使用してサンプリングを行い、ラテンツのテンソルが生成されます。

prompt_embeds (`torch.Tensor`, *任意*) : 事前生成されたテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`prompt` 入力引数からテキスト埋め込みが生成されます。

negative_prompt_embeds (`torch.Tensor`, *任意*) : 事前に生成されたネガティブなテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`negative_prompt` 入力引数から negative_prompt_embeds が生成されます。

pooled_prompt_embeds (`torch.Tensor`, *任意*) : 事前に生成されたプーリング済みテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`prompt` 入力引数からプーリング済みテキスト埋め込みが生成されます。

negative_pooled_prompt_embeds (`torch.Tensor`, *任意*) : 事前に生成されたネガティブなプールのテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`negative_prompt` 入力引数からプールの negative_prompt_embeds が生成されます。

output_type (`str`、*任意*、デフォルトは `"pil"`) : 生成画像の出力形式。[PIL](https://pillow.readthedocs.io/en/stable/)（`PIL.Image.Image`）または `np.array` から選択します。

return_dict (`bool`、*任意*、デフォルトは`True`) : プレーンなタプルではなく`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`を返すかどうか。

callback (`Callable`、*任意*) : 推論中に `callback_steps` ステップごとに呼び出される関数です。この関数は、以下の引数とともに呼び出されます: `callback(step: int, timestep: int, latents: torch.Tensor)`。

callback_steps (`int`、*任意*、デフォルトは 1) : `callback` 関数が呼び出される頻度です。指定しない場合、callback はすべてのステップで呼び出されます。

cross_attention_kwargs (`dict`, *任意*) : 指定された場合、[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) の `self.processor` で定義されている `AttentionProcessor` に渡される kwargs の辞書です。

guidance_rescale (`float`, *optional*, defaults to 0.0) : Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) `guidance_scale` is defined as `φ` in equation 16. of [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891). Guidance rescale factor should fix overexposure when using zero terminal SNR.

original_size (`tuple[int]`、*optional*、デフォルト値は (1024, 1024)) : `original_size` が `target_size` と異なる場合、画像はダウンサンプリングまたはアップサンプリングされたように見えます。`original_size` は、指定されていない場合、デフォルトで `(height, width)` になります。[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952) のセクション 2.2 で説明されている SDXL のマイクロコンディショニングの一部です。

crops_coords_top_left (`tuple[int]`、*optional*、デフォルト値は (0, 0)) : `crops_coords_top_left` を使用すると、`crops_coords_top_left` の位置から下方向に「切り抜かれた」ように見える画像を生成できます。`crops_coords_top_left` を (0, 0) に設定することで、通常は良好で中央が整った画像が得られます。[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952) のセクション 2.2 で説明されている SDXL のマイクロ条件付けの一部です。

target_size (`tuple[int]`、*optional*、デフォルト値は (1024, 1024)) : ほとんどの場合、`target_size` は生成される画像の希望する高さおよび幅に設定する必要があります。指定されない場合、デフォルトで `(height, width)` が使用されます。[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952) のセクション 2.2 で説明されている SDXL のマイクロ条件付けの一部です。

**戻り値:** `~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput` または `tuple`

`return_dict` が True の場合は `~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`、それ以外の場合は `tuple` を返します。tuple を返す場合、最初の要素は生成された画像のリストです。

生成用のパイプラインを呼び出したときに実行される関数。

例:
```py
>>> import torch
>>> from diffusers import StableDiffusionXLInstructPix2PixPipeline
>>> from diffusers.utils import load_image

>>> resolution = 768
>>> image = load_image(
...     "https://hf.co/datasets/diffusers/diffusers-images-docs/resolve/main/mountain.png"
... ).resize((resolution, resolution))
>>> edit_instruction = "Turn sky into a cloudy one"

>>> pipe = StableDiffusionXLInstructPix2PixPipeline.from_pretrained(
...     "diffusers/sdxl-instructpix2pix-768", torch_dtype=torch.float16
... ).to("cuda")

>>> edited_image = pipe(
...     prompt=edit_instruction,
...     image=image,
...     height=resolution,
...     width=resolution,
...     guidance_scale=3.0,
...     image_guidance_scale=1.5,
...     num_inference_steps=30,
... ).images[0]
>>> edited_image
```

#### encode_prompt[[diffusers.StableDiffusionXLInstructPix2PixPipeline.encode_prompt]]

```python
encode_prompt(prompt: str, prompt_2: str | None = None, device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, do_classifier_free_guidance: bool = True, negative_prompt: str | None = None, negative_prompt_2: str | None = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, lora_scale: float | None = None)
```

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py#L213)

**パラメータ:**

prompt (`str` または `list[str]`、*省略可能*) : エンコードするプロンプト

prompt_2 (`str` または `list[str]`、*省略可能*) : `tokenizer_2` および `text_encoder_2` に送信するプロンプトです。未定義の場合、両方のテキストエンコーダーで `prompt` が使用されます。

device : (`torch.device`): torch デバイス

num_images_per_prompt (`int`) : プロンプトごとに生成すべき画像の数

do_classifier_free_guidance (`bool`) : classifier free guidance を使用するかどうか

negative_prompt (`str` または `list[str]`、*省略可能*) : 画像生成をガイドしないプロンプトです。定義されていない場合、代わりに `negative_prompt_embeds` を渡す必要があります。ガイドを使用していない場合は無視されます（`guidance_scale` が `1` 未満の場合は無視されます）。

negative_prompt_2 (`str` または `list[str]`、*省略可*) : `tokenizer_2` および `text_encoder_2` に送信する、画像生成を誘導しないプロンプトです。定義されていない場合、`negative_prompt` が両方のテキストエンコーダーで使用されます。

prompt_embeds (`torch.Tensor`, *任意*) : 事前生成されたテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`prompt` 入力引数からテキスト埋め込みが生成されます。

negative_prompt_embeds (`torch.Tensor`, *任意*) : 事前に生成されたネガティブなテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`negative_prompt` 入力引数から negative_prompt_embeds が生成されます。

pooled_prompt_embeds (`torch.Tensor`, *任意*) : 事前に生成されたプーリング済みテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`prompt` 入力引数からプーリング済みテキスト埋め込みが生成されます。

negative_pooled_prompt_embeds (`torch.Tensor`, *任意*) : 事前に生成されたネガティブなプールのテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`negative_prompt` 入力引数からプールの negative_prompt_embeds が生成されます。

lora_scale (`float`、*任意*) : LoRAレイヤーが読み込まれている場合、テキストエンコーダーのすべてのLoRAレイヤーに適用されるLoRAスケールです。

プロンプトをテキストエンコーダーの隠れ状態にエンコードします。

