# ControlNet

  

ControlNetは、Lvmin Zhang、Anyi Rao、Maneesh Agrawalaによる論文[Adding Conditional Control to Text-to-Image Diffusion Models](https://huggingface.co/papers/2302.05543)で提案されました。

ControlNetモデルを使用すると、Stable Diffusionの生成を条件付け・制御するための追加の制御画像を指定できます。例えば、深度マップを指定した場合、ControlNetモデルは深度マップの空間情報を保持した画像を生成します。これは、画像生成プロセスをより柔軟かつ正確に制御する方法です。

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

*本稿では、大規模な事前学習済みテキストから画像への拡散モデルに空間的条件付け制御を追加するためのニューラルネットワークアーキテクチャであるControlNetを提案します。ControlNetは、実運用可能な大規模拡散モデルを固定し、数十億枚の画像で事前学習された深く頑健なエンコーディング層を強力なバックボーンとして再利用することで、多様な条件付け制御のセットを学習します。このニューラルアーキテクチャは、「ゼロ畳み込み」（ゼロ初期化された畳み込み層）によって接続されており、パラメータをゼロから段階的に増加させ、有害なノイズがファインチューニングに影響を与えないことを保証します。Stable Diffusionを用いて、エッジ、深度、セグメンテーション、人間のポーズなどの様々な条件付け制御を、プロンプトの有無にかかわらず、単一または複数の条件を用いてテストしました。ControlNetの学習は、小規模（<50k）および大規模（>1m）のデータセットのいずれにおいても頑健であることが示されています。広範な結果から、ControlNetは画像拡散モデルの制御に関するより幅広いアプリケーションを促進し得ることが示されました。*

このモデルは [takuma104](https://huggingface.co/takuma104) によって提供されました。❤️

元のコードベースは [lllyasviel/ControlNet](https://github.com/lllyasviel/ControlNet) にあり、公式の ControlNet チェックポイントは [lllyasviel](https://huggingface.co/lllyasviel) の Hub プロファイルで確認できます。

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

## StableDiffusionControlNetPipeline[[diffusers.StableDiffusionControlNetPipeline]]

#### diffusers.StableDiffusionControlNetPipeline[[diffusers.StableDiffusionControlNetPipeline]]

```python
diffusers.StableDiffusionControlNetPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet2DConditionModel, controlnet: diffusers.models.controlnets.controlnet.ControlNetModel | list[diffusers.models.controlnets.controlnet.ControlNetModel] | tuple[diffusers.models.controlnets.controlnet.ControlNetModel] | diffusers.models.controlnets.multicontrolnet.MultiControlNetModel, scheduler: KarrasDiffusionSchedulers, safety_checker: StableDiffusionSafetyChecker, feature_extractor: CLIPImageProcessorPil, image_encoder: CLIPVisionModelWithProjection = None, requires_safety_checker: bool = True)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/controlnet/pipeline_controlnet.py#L162)

**パラメータ:**

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

text_encoder ([CLIPTextModel](https://huggingface.co/docs/transformers/main/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/main/en/model_doc/clip#transformers.CLIPTokenizer)) : テキストをトークン化するための`CLIPTokenizer`。

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

controlnet ([ControlNetModel](/docs/diffusers/main/ja/api/models/controlnet#diffusers.ControlNetModel) または `list[ControlNetModel]`) : デノイジング処理中に `unet` に追加の条件付けを提供します。リストとして複数の ControlNet を設定した場合、各 ControlNet の出力が加算され、1 つの統合された追加条件付けが作成されます。

scheduler ([SchedulerMixin](/docs/diffusers/main/ja/api/schedulers/overview#diffusers.SchedulerMixin)) : `unet` と組み合わせて、エンコードされた画像の潜在変数をデノイズするために使用するスケジューラ。[DDIMScheduler](/docs/diffusers/main/ja/api/schedulers/ddim#diffusers.DDIMScheduler)、[LMSDiscreteScheduler](/docs/diffusers/main/ja/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler)、または [PNDMScheduler](/docs/diffusers/main/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/main/en/model_doc/clip#transformers.CLIPImageProcessor)) : 生成された画像から特徴量を抽出するための`CLIPImageProcessor`。`safety_checker`の入力として使用されます。

ControlNetによるガイダンスを用いたStable Diffusionのテキストから画像への生成を行うPipeline。

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

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

#### __call__[[diffusers.StableDiffusionControlNetPipeline.__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, height: int | None = None, width: int | None = None, num_inference_steps: int = 50, timesteps: list = None, sigmas: list = None, guidance_scale: float = 7.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, cross_attention_kwargs: dict[str, typing.Any] | None = None, controlnet_conditioning_scale: float | list[float] = 1.0, guess_mode: bool = False, control_guidance_start: float | list[float] = 0.0, control_guidance_end: float | list[float] = 1.0, clip_skip: int | None = None, 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 = ['latents'], **kwargs)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/controlnet/pipeline_controlnet.py#L907)

**パラメータ:**

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

image (`torch.Tensor`、`PIL.Image.Image`、`np.ndarray`、`list[torch.Tensor]`、`list[PIL.Image.Image]`、`list[np.ndarray]`、: `list[list[torch.Tensor]]`、`list[list[np.ndarray]]` または `list[list[PIL.Image.Image]]`) 生成時に `unet` へガイダンスを与えるための ControlNet の入力条件です。型が `torch.Tensor` として指定されている場合、ControlNet にそのまま渡されます。画像として `PIL.Image.Image` も受け付けられます。出力画像の寸法は、デフォルトで `image` の寸法になります。高さおよび/または幅が渡された場合、`image` はそれに応じてリサイズされます。`init` で複数の ControlNet が指定されている場合、各 ControlNet への入力が正しくバッチ処理できるよう、画像はリストとして渡す必要があります。`prompt` がリストであり、単一の ControlNet に対して画像のリストが渡された場合、各画像は `prompt` リストの各プロンプトとペアになります。これは複数の ControlNet にも適用され、画像のリストのリストを渡すことで、各プロンプトおよび各 ControlNet ごとにバッチ処理できます。

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) : デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。

timesteps (`list[int]`、*任意*) : `set_timesteps` メソッドで `timesteps` 引数をサポートするスケジューラーにおいて、デノイジングプロセスに使用するカスタムタイムステップ。`num_inference_steps` が渡された場合のデフォルトの動作が使用されます。降順で指定する必要があります。

sigmas (`list[float]`, *任意*) : `set_timesteps` メソッドで `sigmas` 引数をサポートするスケジューラーにおいて、デノイジングプロセスに使用するカスタムシグマ。`num_inference_steps` が渡された場合のデフォルトの動作が使用されます。

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

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/main/ja/api/schedulers/ddim#diffusers.DDIMScheduler)でのみ適用され、他のスケジューラーでは無視されます。

generator (`torch.Generator` または `list[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/main/ja/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput)を返すかどうか。

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

controlnet_conditioning_scale (`float` または `list[float]`、*任意*、デフォルト値は 1.0) : ControlNet の出力は、元の `unet` の残差に加算される前に `controlnet_conditioning_scale` 倍されます。`init` で複数の ControlNet を指定する場合は、対応するスケールをリストとして設定できます。

guess_mode (`bool`、*任意*、デフォルトは`False`) : ControlNet エンコーダーは、すべてのプロンプトを削除した場合でも、入力画像の内容を認識しようとします。`guidance_scale` の値は 3.0 から 5.0 の範囲が推奨されます。

control_guidance_start (`float` または `list[float]`、*任意*、デフォルト値は 0.0) : ControlNet が適用を開始するステップの割合（全体のステップ数に対するパーセンテージ）。

control_guidance_end (`float` または `list[float]`、*任意*、デフォルト値は 1.0) : ControlNet が適用を停止するステップの割合（全体のステップ数に対するパーセンテージ）。

clip_skip (`int`, *optional*) : プロンプト埋め込みを計算する際に、CLIPからスキップするレイヤー数。値が1の場合、プロンプト埋め込みの計算に最終レイヤーの直前のレイヤーの出力が使用されます。

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` 属性に列挙された変数のみを、リストに含めることができます。

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

If `return_dict` is `True`, [StableDiffusionPipelineOutput](/docs/diffusers/main/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
>>> # !pip install opencv-python transformers accelerate
>>> from diffusers import StableDiffusionControlNetPipeline, ControlNetModel, UniPCMultistepScheduler
>>> from diffusers.utils import load_image
>>> import numpy as np
>>> import torch

>>> import cv2
>>> from PIL import Image

>>> # download an image
>>> image = load_image(
...     "https://hf.co/datasets/huggingface/documentation-images/resolve/main/diffusers/input_image_vermeer.png"
... )
>>> image = np.array(image)

>>> # get canny image
>>> image = cv2.Canny(image, 100, 200)
>>> image = image[:, :, None]
>>> image = np.concatenate([image, image, image], axis=2)
>>> canny_image = Image.fromarray(image)

>>> # load control net and stable diffusion v1-5
>>> controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16)
>>> pipe = StableDiffusionControlNetPipeline.from_pretrained(
...     "stable-diffusion-v1-5/stable-diffusion-v1-5", controlnet=controlnet, torch_dtype=torch.float16
... )

>>> # speed up diffusion process with faster scheduler and memory optimization
>>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
>>> # remove following line if xformers is not installed
>>> pipe.enable_xformers_memory_efficient_attention()

>>> pipe.enable_model_cpu_offload()

>>> # generate image
>>> generator = torch.manual_seed(0)
>>> image = pipe(
...     "futuristic-looking woman", num_inference_steps=20, generator=generator, image=canny_image
... ).images[0]
```

#### enable_attention_slicing[[diffusers.StableDiffusionControlNetPipeline.enable_attention_slicing]]

```python
enable_attention_slicing(slice_size: str | int = 'auto')
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pipeline_utils.py#L2048)

**パラメータ:**

slice_size (`str` または `int`、*任意*、デフォルトは `"auto"`) : `"auto"` の場合、アテンションヘッドへの入力を半分にし、アテンションを2段階で計算します。`"max"` の場合、一度に1つのスライスのみを実行することで、最大限のメモリを節約します。数値が指定された場合、`attention_head_dim // slice_size` 個のスライスを 사용합니다。この場合、`attention_head_dim` は `slice_size` の倍数である必要があります。

スライスされたアテンション計算を有効にします。このオプションを有効にすると、アテンションモジュールは入力テンソルをスライスに分割し、複数ステップでアテンションを計算します。アテンションヘッドが1つを超える場合、各ヘッドに対して計算が順次実行されます。これは、わずかな速度低下を代償にメモリを節約するために有用です。

> [!WARNING] > ⚠️ `scaled_dot_product_attention`（SDPA）をすでに使用している場合は、attention slicing を有効にしないでください
PyTorch > 2.0 または xFormers から。これらのアテンション計算はすでに非常にメモリ効率が高いため、この機能を有効にする必要はありません。SDPA または xFormers でアテンションスライシングを有効にすると、重大なスローダウンを引き起こす可能性があります!

例:

```py
>>> import torch
>>> from diffusers import StableDiffusionPipeline

>>> pipe = StableDiffusionPipeline.from_pretrained(
...     "stable-diffusion-v1-5/stable-diffusion-v1-5",
...     dtype=torch.float16,
...     use_safetensors=True,
... )

>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> pipe.enable_attention_slicing()
>>> image = pipe(prompt).images[0]
```

#### disable_attention_slicing[[diffusers.StableDiffusionControlNetPipeline.disable_attention_slicing]]

```python
disable_attention_slicing()
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pipeline_utils.py#L2085)

スライスされたアテンションの計算を無効にします。`enable_attention_slicing`が以前に呼び出されていた場合、アテンションは1ステップで計算されます。

#### enable_xformers_memory_efficient_attention[[diffusers.StableDiffusionControlNetPipeline.enable_xformers_memory_efficient_attention]]

```python
enable_xformers_memory_efficient_attention(attention_op: typing.Optional[typing.Callable] = None)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pipeline_utils.py#L1993)

**パラメータ:**

attention_op (`Callable`、*任意*) : xFormers の [`memory_efficient_attention()`](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.memory_efficient_attention) 関数の `op` 引数として使用するために、デフォルトの `None` オペレーターをオーバーライドします。

[xFormers](https://facebookresearch.github.io/xformers/)からメモリ効率の高いアテンションを有効にします。このオプションを有効にすると、GPUメモリ使用量の低下と、推論時の処理速度の向上が期待できます。ただし、学習時の処理速度向上は保証されません。

> [!WARNING] > ⚠️ メモリ効率の良いアテンションとスライスされたアテンションの両方が有効な場合、メモリ効率
attention は > に優先します。

例:

```py
>>> import torch
>>> from diffusers import DiffusionPipeline
>>> from xformers.ops import MemoryEfficientAttentionFlashAttentionOp

>>> pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1", dtype=torch.float16)
>>> pipe = pipe.to("cuda")
>>> pipe.enable_xformers_memory_efficient_attention(attention_op=MemoryEfficientAttentionFlashAttentionOp)
>>> # Workaround for not accepting attention shape using VAE for Flash Attention
>>> pipe.vae.enable_xformers_memory_efficient_attention(attention_op=None)
```

#### disable_xformers_memory_efficient_attention[[diffusers.StableDiffusionControlNetPipeline.disable_xformers_memory_efficient_attention]]

```python
disable_xformers_memory_efficient_attention()
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pipeline_utils.py#L2024)

[xFormers](https://facebookresearch.github.io/xformers/)からのメモリ効率の高いアテンションを無効にします。

#### load_textual_inversion[[diffusers.StableDiffusionControlNetPipeline.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/main/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/main/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/main/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/main/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")
```

#### encode_prompt[[diffusers.StableDiffusionControlNetPipeline.encode_prompt]]

```python
encode_prompt(prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, lora_scale: float | None = None, clip_skip: int | None = None)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/controlnet/pipeline_controlnet.py#L298)

**パラメータ:**

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

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` 未満の場合は無視されます）。

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

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

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

clip_skip (`int`, *optional*) : プロンプト埋め込みを計算する際に、CLIPからスキップするレイヤー数。値が1の場合、プロンプト埋め込みの計算に最終レイヤーの直前のレイヤーの出力が使用されます。

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

#### get_guidance_scale_embedding[[diffusers.StableDiffusionControlNetPipeline.get_guidance_scale_embedding]]

```python
get_guidance_scale_embedding(w: Tensor, embedding_dim: int = 512, dtype: dtype = torch.float32)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/controlnet/pipeline_controlnet.py#L850)

**パラメータ:**

w (`torch.Tensor`) : 指定されたガイダンススケールで埋め込みベクトルを生成し、タイムステップ埋め込みを後で強化します。

embedding_dim (`int`、*任意*、デフォルトは 512) : 生成する埋め込みの次元数。

dtype (`torch.dtype`、*任意*、デフォルトは`torch.float32`) : 生成される埋め込みのデータ型。

**戻り値:** `torch.Tensor`

`(len(w), embedding_dim)` の形状を持つ埋め込みベクトル。

https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298 を参照してください。

## StableDiffusionControlNetImg2ImgPipeline[[diffusers.StableDiffusionControlNetImg2ImgPipeline]]

#### diffusers.StableDiffusionControlNetImg2ImgPipeline[[diffusers.StableDiffusionControlNetImg2ImgPipeline]]

```python
diffusers.StableDiffusionControlNetImg2ImgPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet2DConditionModel, controlnet: diffusers.models.controlnets.controlnet.ControlNetModel | list[diffusers.models.controlnets.controlnet.ControlNetModel] | tuple[diffusers.models.controlnets.controlnet.ControlNetModel] | diffusers.models.controlnets.multicontrolnet.MultiControlNetModel, scheduler: KarrasDiffusionSchedulers, safety_checker: StableDiffusionSafetyChecker, feature_extractor: CLIPImageProcessorPil, image_encoder: CLIPVisionModelWithProjection = None, requires_safety_checker: bool = True)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py#L140)

**パラメータ:**

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

text_encoder ([CLIPTextModel](https://huggingface.co/docs/transformers/main/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/main/en/model_doc/clip#transformers.CLIPTokenizer)) : テキストをトークン化するための`CLIPTokenizer`。

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

controlnet ([ControlNetModel](/docs/diffusers/main/ja/api/models/controlnet#diffusers.ControlNetModel) または `list[ControlNetModel]`) : デノイジング処理中に `unet` に追加の条件付けを提供します。リストとして複数の ControlNet を設定した場合、各 ControlNet の出力が加算され、1 つの統合された追加条件付けが作成されます。

scheduler ([SchedulerMixin](/docs/diffusers/main/ja/api/schedulers/overview#diffusers.SchedulerMixin)) : `unet` と組み合わせて、エンコードされた画像の潜在変数をデノイズするために使用するスケジューラ。[DDIMScheduler](/docs/diffusers/main/ja/api/schedulers/ddim#diffusers.DDIMScheduler)、[LMSDiscreteScheduler](/docs/diffusers/main/ja/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler)、または [PNDMScheduler](/docs/diffusers/main/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/main/en/model_doc/clip#transformers.CLIPImageProcessor)) : 生成された画像から特徴量を抽出するための`CLIPImageProcessor`。`safety_checker`の入力として使用されます。

ControlNetによるガイダンスを用いたStable Diffusionの画像から画像への生成を行うPipeline。

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

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

#### __call__[[diffusers.StableDiffusionControlNetImg2ImgPipeline.__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, control_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, strength: float = 0.8, num_inference_steps: int = 50, guidance_scale: float = 7.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, cross_attention_kwargs: dict[str, typing.Any] | None = None, controlnet_conditioning_scale: float | list[float] = 0.8, guess_mode: bool = False, control_guidance_start: float | list[float] = 0.0, control_guidance_end: float | list[float] = 1.0, clip_skip: int | None = None, 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 = ['latents'], **kwargs)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py#L905)

**パラメータ:**

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

image (`torch.Tensor`、`PIL.Image.Image`、`np.ndarray`、`list[torch.Tensor]`、`list[PIL.Image.Image]`、`list[np.ndarray]`、: `list[list[torch.Tensor]]`、`list[list[np.ndarray]]` または `list[list[PIL.Image.Image]]`)：画像生成プロセスの開始点として使用される初期画像です。`image` として画像の潜在変数（latents）を受け取ることもでき、潜在変数を直接渡す場合は再度エンコードされません。

control_image (`torch.Tensor`、`PIL.Image.Image`、`np.ndarray`、`list[torch.Tensor]`、`list[PIL.Image.Image]`、`list[np.ndarray]`、: `list[list[torch.Tensor]]`、`list[list[np.ndarray]]` または `list[list[PIL.Image.Image]]`): 生成において `unet` にガイダンスを与えるための ControlNet の入力条件です。型が `torch.Tensor` として指定されている場合、ControlNet にそのまま渡されます。画像として `PIL.Image.Image` も受け付けられます。出力画像の寸法は、デフォルトで `image` の寸法になります。高さおよび/または幅が渡された場合、`image` はそれに応じてリサイズされます。`init` で複数の ControlNet が指定されている場合、各 ControlNet への入力が正しくバッチ処理できるよう、リストとして画像を渡す必要があります。

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

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

strength (`float`、*任意*、デフォルト値は 0.8) : 参照となる`image`の変換の程度を示します。0 から 1 の間の値である必要があります。`image`は開始点として使用され、`strength`が大きいほど多くのノイズが追加されます。デノイジングのステップ数は、最初に追加されるノイズの量に依存します。`strength`が 1 の場合、追加されるノイズは最大となり、デノイジングプロセスは`num_inference_steps`で指定された全イテレーション数分実行されます。値が 1 である場合、`image`は実質的に無視されます。

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

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

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/main/ja/api/schedulers/ddim#diffusers.DDIMScheduler)でのみ適用され、他のスケジューラーでは無視されます。

generator (`torch.Generator` または `list[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/main/ja/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput)を返すかどうか。

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

controlnet_conditioning_scale (`float` または `list[float]`、*任意*、デフォルト値は 1.0) : ControlNet の出力は、元の `unet` の残差に加算される前に `controlnet_conditioning_scale` 倍されます。`init` で複数の ControlNet を指定する場合は、対応するスケールをリストとして設定できます。

guess_mode (`bool`、*任意*、デフォルトは`False`) : ControlNet エンコーダーは、すべてのプロンプトを削除した場合でも、入力画像の内容を認識しようとします。`guidance_scale` の値は 3.0 から 5.0 の範囲が推奨されます。

control_guidance_start (`float` または `list[float]`、*任意*、デフォルト値は 0.0) : ControlNet が適用を開始するステップの割合（全体のステップ数に対するパーセンテージ）。

control_guidance_end (`float` または `list[float]`、*任意*、デフォルト値は 1.0) : ControlNet が適用を停止するステップの割合（全体のステップ数に対するパーセンテージ）。

clip_skip (`int`, *optional*) : プロンプト埋め込みを計算する際に、CLIPからスキップするレイヤー数。値が1の場合、プロンプト埋め込みの計算に最終レイヤーの直前のレイヤーの出力が使用されます。

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` 属性に列挙された変数のみを、リストに含めることができます。

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

If `return_dict` is `True`, [StableDiffusionPipelineOutput](/docs/diffusers/main/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
>>> # !pip install opencv-python transformers accelerate
>>> from diffusers import StableDiffusionControlNetImg2ImgPipeline, ControlNetModel, UniPCMultistepScheduler
>>> from diffusers.utils import load_image
>>> import numpy as np
>>> import torch

>>> import cv2
>>> from PIL import Image

>>> # download an image
>>> image = load_image(
...     "https://hf.co/datasets/huggingface/documentation-images/resolve/main/diffusers/input_image_vermeer.png"
... )
>>> np_image = np.array(image)

>>> # get canny image
>>> np_image = cv2.Canny(np_image, 100, 200)
>>> np_image = np_image[:, :, None]
>>> np_image = np.concatenate([np_image, np_image, np_image], axis=2)
>>> canny_image = Image.fromarray(np_image)

>>> # load control net and stable diffusion v1-5
>>> controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16)
>>> pipe = StableDiffusionControlNetImg2ImgPipeline.from_pretrained(
...     "stable-diffusion-v1-5/stable-diffusion-v1-5", controlnet=controlnet, torch_dtype=torch.float16
... )

>>> # speed up diffusion process with faster scheduler and memory optimization
>>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
>>> pipe.enable_model_cpu_offload()

>>> # generate image
>>> generator = torch.manual_seed(0)
>>> image = pipe(
...     "futuristic-looking woman",
...     num_inference_steps=20,
...     generator=generator,
...     image=image,
...     control_image=canny_image,
... ).images[0]
```

#### enable_attention_slicing[[diffusers.StableDiffusionControlNetImg2ImgPipeline.enable_attention_slicing]]

```python
enable_attention_slicing(slice_size: str | int = 'auto')
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pipeline_utils.py#L2048)

**パラメータ:**

slice_size (`str` または `int`、*任意*、デフォルトは `"auto"`) : `"auto"` の場合、アテンションヘッドへの入力を半分にし、アテンションを2段階で計算します。`"max"` の場合、一度に1つのスライスのみを実行することで、最大限のメモリを節約します。数値が指定された場合、`attention_head_dim // slice_size` 個のスライスを 사용합니다。この場合、`attention_head_dim` は `slice_size` の倍数である必要があります。

スライスされたアテンション計算を有効にします。このオプションを有効にすると、アテンションモジュールは入力テンソルをスライスに分割し、複数ステップでアテンションを計算します。アテンションヘッドが1つを超える場合、各ヘッドに対して計算が順次実行されます。これは、わずかな速度低下を代償にメモリを節約するために有用です。

> [!WARNING] > ⚠️ `scaled_dot_product_attention`（SDPA）をすでに使用している場合は、attention slicing を有効にしないでください
PyTorch > 2.0 または xFormers から。これらのアテンション計算はすでに非常にメモリ効率が高いため、この機能を有効にする必要はありません。SDPA または xFormers でアテンションスライシングを有効にすると、重大なスローダウンを引き起こす可能性があります!

例:

```py
>>> import torch
>>> from diffusers import StableDiffusionPipeline

>>> pipe = StableDiffusionPipeline.from_pretrained(
...     "stable-diffusion-v1-5/stable-diffusion-v1-5",
...     dtype=torch.float16,
...     use_safetensors=True,
... )

>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> pipe.enable_attention_slicing()
>>> image = pipe(prompt).images[0]
```

#### disable_attention_slicing[[diffusers.StableDiffusionControlNetImg2ImgPipeline.disable_attention_slicing]]

```python
disable_attention_slicing()
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pipeline_utils.py#L2085)

スライスされたアテンションの計算を無効にします。`enable_attention_slicing`が以前に呼び出されていた場合、アテンションは1ステップで計算されます。

#### enable_xformers_memory_efficient_attention[[diffusers.StableDiffusionControlNetImg2ImgPipeline.enable_xformers_memory_efficient_attention]]

```python
enable_xformers_memory_efficient_attention(attention_op: typing.Optional[typing.Callable] = None)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pipeline_utils.py#L1993)

**パラメータ:**

attention_op (`Callable`、*任意*) : xFormers の [`memory_efficient_attention()`](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.memory_efficient_attention) 関数の `op` 引数として使用するために、デフォルトの `None` オペレーターをオーバーライドします。

[xFormers](https://facebookresearch.github.io/xformers/)からメモリ効率の高いアテンションを有効にします。このオプションを有効にすると、GPUメモリ使用量の低下と、推論時の処理速度の向上が期待できます。ただし、学習時の処理速度向上は保証されません。

> [!WARNING] > ⚠️ メモリ効率の良いアテンションとスライスされたアテンションの両方が有効な場合、メモリ効率
attention は > に優先します。

例:

```py
>>> import torch
>>> from diffusers import DiffusionPipeline
>>> from xformers.ops import MemoryEfficientAttentionFlashAttentionOp

>>> pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1", dtype=torch.float16)
>>> pipe = pipe.to("cuda")
>>> pipe.enable_xformers_memory_efficient_attention(attention_op=MemoryEfficientAttentionFlashAttentionOp)
>>> # Workaround for not accepting attention shape using VAE for Flash Attention
>>> pipe.vae.enable_xformers_memory_efficient_attention(attention_op=None)
```

#### disable_xformers_memory_efficient_attention[[diffusers.StableDiffusionControlNetImg2ImgPipeline.disable_xformers_memory_efficient_attention]]

```python
disable_xformers_memory_efficient_attention()
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pipeline_utils.py#L2024)

[xFormers](https://facebookresearch.github.io/xformers/)からのメモリ効率の高いアテンションを無効にします。

#### load_textual_inversion[[diffusers.StableDiffusionControlNetImg2ImgPipeline.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/main/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/main/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/main/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/main/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")
```

#### encode_prompt[[diffusers.StableDiffusionControlNetImg2ImgPipeline.encode_prompt]]

```python
encode_prompt(prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, lora_scale: float | None = None, clip_skip: int | None = None)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py#L276)

**パラメータ:**

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

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` 未満の場合は無視されます）。

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

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

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

clip_skip (`int`, *optional*) : プロンプト埋め込みを計算する際に、CLIPからスキップするレイヤー数。値が1の場合、プロンプト埋め込みの計算に最終レイヤーの直前のレイヤーの出力が使用されます。

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

## StableDiffusionControlNetInpaintPipeline[[diffusers.StableDiffusionControlNetInpaintPipeline]]

#### diffusers.StableDiffusionControlNetInpaintPipeline[[diffusers.StableDiffusionControlNetInpaintPipeline]]

```python
diffusers.StableDiffusionControlNetInpaintPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet2DConditionModel, controlnet: diffusers.models.controlnets.controlnet.ControlNetModel | list[diffusers.models.controlnets.controlnet.ControlNetModel] | tuple[diffusers.models.controlnets.controlnet.ControlNetModel] | diffusers.models.controlnets.multicontrolnet.MultiControlNetModel, scheduler: KarrasDiffusionSchedulers, safety_checker: StableDiffusionSafetyChecker, feature_extractor: CLIPImageProcessorPil, image_encoder: CLIPVisionModelWithProjection = None, requires_safety_checker: bool = True)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py#L128)

**パラメータ:**

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

text_encoder ([CLIPTextModel](https://huggingface.co/docs/transformers/main/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/main/en/model_doc/clip#transformers.CLIPTokenizer)) : テキストをトークン化するための`CLIPTokenizer`。

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

controlnet ([ControlNetModel](/docs/diffusers/main/ja/api/models/controlnet#diffusers.ControlNetModel) または `list[ControlNetModel]`) : デノイジング処理中に `unet` に追加の条件付けを提供します。リストとして複数の ControlNet を設定した場合、各 ControlNet の出力が加算され、1 つの統合された追加条件付けが作成されます。

scheduler ([SchedulerMixin](/docs/diffusers/main/ja/api/schedulers/overview#diffusers.SchedulerMixin)) : `unet` と組み合わせて、エンコードされた画像の潜在変数をデノイズするために使用するスケジューラ。[DDIMScheduler](/docs/diffusers/main/ja/api/schedulers/ddim#diffusers.DDIMScheduler)、[LMSDiscreteScheduler](/docs/diffusers/main/ja/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler)、または [PNDMScheduler](/docs/diffusers/main/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/main/en/model_doc/clip#transformers.CLIPImageProcessor)) : 生成された画像から特徴量を抽出するための`CLIPImageProcessor`。`safety_checker`の入力として使用されます。

ControlNetのガイダンスを用いたStable Diffusionによる画像インペインティングのパイプライン。

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

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

> [!TIP] > このパイプラインは、インペインティング用に特別にファインチューニングされたチェックポイントと組み合わせて使用できます >
([stable-diffusion-v1-5/stable-diffusion-inpainting](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-inpainting))
> as well as default text-to-image Stable Diffusion checkpoints >
([stable-diffusion-v1-5/stable-diffusion-v1-5](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5))。
> ControlNetのファインチューニングが施されている場合、デフォルトのテキストから画像への変換用Stable Diffusionチェックポイントの方が好ましい場合があります
それら、例えば [lllyasviel/control_v11p_sd15_inpaint](https://huggingface.co/lllyasviel/control_v11p_sd15_inpaint) などです。

#### __call__[[diffusers.StableDiffusionControlNetInpaintPipeline.__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, mask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, control_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, padding_mask_crop: int | None = None, strength: float = 1.0, num_inference_steps: int = 50, guidance_scale: float = 7.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, cross_attention_kwargs: dict[str, typing.Any] | None = None, controlnet_conditioning_scale: float | list[float] = 0.5, guess_mode: bool = False, control_guidance_start: float | list[float] = 0.0, control_guidance_end: float | list[float] = 1.0, clip_skip: int | None = None, 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 = ['latents'], **kwargs)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py#L994)

**パラメータ:**

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

image (`torch.Tensor`、`PIL.Image.Image`、`np.ndarray`、`list[torch.Tensor]`、`list[PIL.Image.Image]`、または `list[np.ndarray]`): 開始点として使用する画像バッチを表す `Image`、NumPy 配列、またはテンソル。NumPy 配列および PyTorch テンソルの両方において、想定される値の範囲は `[0, 1]` です。テンソルまたはテンソルのリストの場合、想定される形状は `(B, C, H, W)` または `(C, H, W)` です。NumPy 配列または配列のリストの場合、想定される形状は `(B, H, W, C)` または `(H, W, C)` です。また、`image` として画像の潜在変数（latents）を受け取ることができますが、潜在変数を直接渡す場合は、再度エンコードされません。

mask_image (`torch.Tensor`、`PIL.Image.Image`、`np.ndarray`、`list[torch.Tensor]`、`list[PIL.Image.Image]`、または `list[np.ndarray]`)：`Image`、NumPy 配列、またはテンソル。マスクに使用する `image` のバッチを表します。マスク内の白いピクセルは再描画され、黒いピクセルは保持されます。`mask_image` が PIL 画像の場合、使用の前に単一チャネル（輝度）に変換されます。NumPy 配列または PyTorch テンソルの場合は、3 つのカラーチャネルではなく 1 つのカラーチャネル（L）を含む必要があります。したがって、PyTorch テンソルの想定される形状は `(B, 1, H, W)`、`(B, H, W)`、`(1, H, W)`、`(H, W)` となります。NumPy 配列の場合は、`(B, H, W, 1)`、`(B, H, W)`、`(H, W, 1)`、または `(H, W)` となります。

control_image (`torch.Tensor`、`PIL.Image.Image`、`list[torch.Tensor]`、`list[PIL.Image.Image]`、: `list[list[torch.Tensor]]`、または `list[list[PIL.Image.Image]]`): 生成時に`unet`へのガイダンスを提供するための ControlNet の入力条件です。型が`torch.Tensor`として指定されている場合、ControlNet にそのまま渡されます。`PIL.Image.Image`も画像として受け付けられます。出力画像の寸法は、デフォルトで`image`の寸法になります。高さおよび/または幅が渡された場合、`image`はそれに合わせてリサイズされます。`init`で複数の ControlNet が指定されている場合、リストとして画像を渡す必要があり、リストの各要素が単一の ControlNet への入力として正しくバッチ処理できるようにしてください。

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

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

padding_mask_crop (`int`, *任意*、デフォルトは `None`) : 画像とマスクに適用するクロップの余白サイズ。`None` の場合、画像および mask_image にはクロップが適用されません。`padding_mask_crop` が `None` でない場合、まず画像と同じアスペクト比を持ち、すべてのマスク領域を含む長方形の領域を特定し、その後 `padding_mask_crop` に基づいてその領域を拡大します。その後、インペインティングのために元の画像サイズにリサイズする前に、拡大された領域に基づいて画像と mask_image がクロップされます。これは、マスク領域が小さく、画像が大きく、背景などインペインティングに関連しない情報が含まれている場合に有用です。

strength (`float`、*任意*、デフォルト値は 1.0) : 参照となる `image` を変換する度合いを示します。0 から 1 の間の値である必要があります。`image` が起点として使用され、`strength` の値が大きいほど、より多くのノイズが追加されます。デノイジングのステップ数は、最初に追加されるノイズの量に依存します。`strength` が 1 の場合、追加されるノイズは最大となり、`num_inference_steps` で指定された全イテレーション数にわたってデノイジングプロセスが実行されます。値が 1 である場合、`image` は実質的に無視されます。

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

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

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/main/ja/api/schedulers/ddim#diffusers.DDIMScheduler)でのみ適用され、他のスケジューラーでは無視されます。

generator (`torch.Generator` または `list[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/main/ja/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput)を返すかどうか。

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

controlnet_conditioning_scale (`float` または `list[float]`、*任意*、デフォルト値は 0.5) : ControlNet の出力は、元の `unet` の残差に加算される前に `controlnet_conditioning_scale` 倍されます。`init` で複数の ControlNet が指定されている場合、対応するスケールをリストとして設定できます。

guess_mode (`bool`、*任意*、デフォルトは`False`) : ControlNet エンコーダーは、すべてのプロンプトを削除した場合でも、入力画像の内容を認識しようとします。`guidance_scale` の値は 3.0 から 5.0 の範囲が推奨されます。

control_guidance_start (`float` または `list[float]`、*任意*、デフォルト値は 0.0) : ControlNet が適用を開始するステップの割合（全体のステップ数に対するパーセンテージ）。

control_guidance_end (`float` または `list[float]`、*任意*、デフォルト値は 1.0) : ControlNet が適用を停止するステップの割合（全体のステップ数に対するパーセンテージ）。

clip_skip (`int`, *optional*) : プロンプト埋め込みを計算する際に、CLIPからスキップするレイヤー数。値が1の場合、プロンプト埋め込みの計算に最終レイヤーの直前のレイヤーの出力が使用されます。

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` 属性に列挙された変数のみを、リストに含めることができます。

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

If `return_dict` is `True`, [StableDiffusionPipelineOutput](/docs/diffusers/main/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
>>> # !pip install transformers accelerate
>>> from diffusers import StableDiffusionControlNetInpaintPipeline, ControlNetModel, DDIMScheduler
>>> from diffusers.utils import load_image
>>> import numpy as np
>>> import torch

>>> init_image = load_image(
...     "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_inpaint/boy.png"
... )
>>> init_image = init_image.resize((512, 512))

>>> generator = torch.Generator(device="cpu").manual_seed(1)

>>> mask_image = load_image(
...     "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_inpaint/boy_mask.png"
... )
>>> mask_image = mask_image.resize((512, 512))

>>> def make_canny_condition(image):
...     image = np.array(image)
...     image = cv2.Canny(image, 100, 200)
...     image = image[:, :, None]
...     image = np.concatenate([image, image, image], axis=2)
...     image = Image.fromarray(image)
...     return image

>>> control_image = make_canny_condition(init_image)

>>> controlnet = ControlNetModel.from_pretrained(
...     "lllyasviel/control_v11p_sd15_inpaint", torch_dtype=torch.float16
... )
>>> pipe = StableDiffusionControlNetInpaintPipeline.from_pretrained(
...     "stable-diffusion-v1-5/stable-diffusion-v1-5", controlnet=controlnet, torch_dtype=torch.float16
... )

>>> pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
>>> pipe.enable_model_cpu_offload()

>>> # generate image
>>> image = pipe(
...     "a handsome man with ray-ban sunglasses",
...     num_inference_steps=20,
...     generator=generator,
...     eta=1.0,
...     image=init_image,
...     mask_image=mask_image,
...     control_image=control_image,
... ).images[0]
```

#### enable_attention_slicing[[diffusers.StableDiffusionControlNetInpaintPipeline.enable_attention_slicing]]

```python
enable_attention_slicing(slice_size: str | int = 'auto')
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pipeline_utils.py#L2048)

**パラメータ:**

slice_size (`str` または `int`、*任意*、デフォルトは `"auto"`) : `"auto"` の場合、アテンションヘッドへの入力を半分にし、アテンションを2段階で計算します。`"max"` の場合、一度に1つのスライスのみを実行することで、最大限のメモリを節約します。数値が指定された場合、`attention_head_dim // slice_size` 個のスライスを 사용합니다。この場合、`attention_head_dim` は `slice_size` の倍数である必要があります。

スライスされたアテンション計算を有効にします。このオプションを有効にすると、アテンションモジュールは入力テンソルをスライスに分割し、複数ステップでアテンションを計算します。アテンションヘッドが1つを超える場合、各ヘッドに対して計算が順次実行されます。これは、わずかな速度低下を代償にメモリを節約するために有用です。

> [!WARNING] > ⚠️ `scaled_dot_product_attention`（SDPA）をすでに使用している場合は、attention slicing を有効にしないでください
PyTorch > 2.0 または xFormers から。これらのアテンション計算はすでに非常にメモリ効率が高いため、この機能を有効にする必要はありません。SDPA または xFormers でアテンションスライシングを有効にすると、重大なスローダウンを引き起こす可能性があります!

例:

```py
>>> import torch
>>> from diffusers import StableDiffusionPipeline

>>> pipe = StableDiffusionPipeline.from_pretrained(
...     "stable-diffusion-v1-5/stable-diffusion-v1-5",
...     dtype=torch.float16,
...     use_safetensors=True,
... )

>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> pipe.enable_attention_slicing()
>>> image = pipe(prompt).images[0]
```

#### disable_attention_slicing[[diffusers.StableDiffusionControlNetInpaintPipeline.disable_attention_slicing]]

```python
disable_attention_slicing()
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pipeline_utils.py#L2085)

スライスされたアテンションの計算を無効にします。`enable_attention_slicing`が以前に呼び出されていた場合、アテンションは1ステップで計算されます。

#### enable_xformers_memory_efficient_attention[[diffusers.StableDiffusionControlNetInpaintPipeline.enable_xformers_memory_efficient_attention]]

```python
enable_xformers_memory_efficient_attention(attention_op: typing.Optional[typing.Callable] = None)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pipeline_utils.py#L1993)

**パラメータ:**

attention_op (`Callable`、*任意*) : xFormers の [`memory_efficient_attention()`](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.memory_efficient_attention) 関数の `op` 引数として使用するために、デフォルトの `None` オペレーターをオーバーライドします。

[xFormers](https://facebookresearch.github.io/xformers/)からメモリ効率の高いアテンションを有効にします。このオプションを有効にすると、GPUメモリ使用量の低下と、推論時の処理速度の向上が期待できます。ただし、学習時の処理速度向上は保証されません。

> [!WARNING] > ⚠️ メモリ効率の良いアテンションとスライスされたアテンションの両方が有効な場合、メモリ効率
attention は > に優先します。

例:

```py
>>> import torch
>>> from diffusers import DiffusionPipeline
>>> from xformers.ops import MemoryEfficientAttentionFlashAttentionOp

>>> pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1", dtype=torch.float16)
>>> pipe = pipe.to("cuda")
>>> pipe.enable_xformers_memory_efficient_attention(attention_op=MemoryEfficientAttentionFlashAttentionOp)
>>> # Workaround for not accepting attention shape using VAE for Flash Attention
>>> pipe.vae.enable_xformers_memory_efficient_attention(attention_op=None)
```

#### disable_xformers_memory_efficient_attention[[diffusers.StableDiffusionControlNetInpaintPipeline.disable_xformers_memory_efficient_attention]]

```python
disable_xformers_memory_efficient_attention()
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pipeline_utils.py#L2024)

[xFormers](https://facebookresearch.github.io/xformers/)からのメモリ効率の高いアテンションを無効にします。

#### load_textual_inversion[[diffusers.StableDiffusionControlNetInpaintPipeline.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/main/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/main/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/main/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/main/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")
```

#### encode_prompt[[diffusers.StableDiffusionControlNetInpaintPipeline.encode_prompt]]

```python
encode_prompt(prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, lora_scale: float | None = None, clip_skip: int | None = None)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py#L282)

**パラメータ:**

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

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` 未満の場合は無視されます）。

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

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

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

clip_skip (`int`, *optional*) : プロンプト埋め込みを計算する際に、CLIPからスキップするレイヤー数。値が1の場合、プロンプト埋め込みの計算に最終レイヤーの直前のレイヤーの出力が使用されます。

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

## StableDiffusionPipelineOutput[[diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput]]

#### diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput[[diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput]]

```python
diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput(images: list[PIL.Image.Image] | numpy.ndarray, nsfw_content_detected: list[bool] | None)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_output.py#L10)

**パラメータ:**

images (`list[PIL.Image.Image]` または `np.ndarray`) : 長さ `batch_size` のノイズ除去済み PIL 画像のリスト、または形状 `(batch_size, height, width, num_channels)` の NumPy 配列。

nsfw_content_detected (`list[bool]`) : 対応する生成画像に「not-safe-for-work」（nsfw）コンテンツが含まれるかどうかを示すリスト。安全性チェックを実行できなかった場合は`None`。

Stable Diffusion パイプライン用の出力クラスです。

