# インペインティング

  

Stable Diffusion モデルはインペインティングにも適用でき、マスクとテキストプロンプトを指定することで、画像の特定の部分を編集できます。

## ヒント

インペインティング用に特別にファインチューニングされたチェックポイント、例えば [stable-diffusion-v1-5/stable-diffusion-inpainting](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-inpainting) と組み合わせてこのパイプラインを使用することをお勧めします。デフォルトのテキストから画像への変換 Stable Diffusion チェックポイント、例えば [stable-diffusion-v1-5/stable-diffusion-v1-5](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5) も互換性がありますが、パフォーマンスが劣る場合があります。

> [!TIP]
> スケジューラーの速度と品質のトレードオフをどのように探索するか、またパイプラインのコンポーネントを効率的に再利用する方法を学ぶために、Stable Diffusionの[Tips](overview#tips)セクションをぜひご確認ください。
>
> タスクに公式チェックポイントのいずれかを使用する場合は、[CompVis](https://huggingface.co/CompVis) と [Stability AI](https://huggingface.co/stabilityai) の Hub 組織を探索してください!

## StableDiffusionInpaintPipeline[[diffusers.StableDiffusionInpaintPipeline]]

#### diffusers.StableDiffusionInpaintPipeline[[diffusers.StableDiffusionInpaintPipeline]]

```python
diffusers.StableDiffusionInpaintPipeline(vae: diffusers.models.autoencoders.autoencoder_kl.AutoencoderKL | diffusers.models.autoencoders.autoencoder_asym_kl.AsymmetricAutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet2DConditionModel, 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/stable_diffusion/pipeline_stable_diffusion_inpaint.py#L128)

**パラメータ:**

vae ([`AutoencoderKL`, `AsymmetricAutoencoderKL`]) : 画像を潜在表現にエンコードし、潜在表現からデコードするための Variational Auto-Encoder (VAE) モデル。

text_encoder (`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`。

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`の入力として使用されます。

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)を使用します
- IP Adapterの読み込みに[load_ip_adapter()](/docs/diffusers/main/ja/api/loaders/ip_adapter#diffusers.loaders.IPAdapterMixin.load_ip_adapter)
- `.ckpt`ファイルを読み込むための[from_single_file()](/docs/diffusers/main/ja/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file)

#### __call__[[diffusers.StableDiffusionInpaintPipeline.__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, masked_image_latents: 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, timesteps: list[int] = None, sigmas: list[float] = 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, clip_skip: int = 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[str] = ['latents'], **kwargs)
```

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

**パラメータ:**

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 配列、またはテンソル。インペイントする画像のバッチを表します（`mask_image` でマスクアウトする部分と、`prompt` に従って再描画する部分）。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` をマスクするための `Image`、numpy 配列、またはテンソル。マスク内の白いピクセルは再描画され、黒いピクセルは保持されます。`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)` となります。

masked_image_latents (`torch.Tensor`, *任意*) : マスクされた画像の事前エンコード済み潜在変数（インペインティング用）。

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

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 の辞書です。

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
>>> import PIL
>>> import requests
>>> import torch
>>> from io import BytesIO

>>> from diffusers import StableDiffusionInpaintPipeline

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

>>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
>>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"

>>> init_image = download_image(img_url).resize((512, 512))
>>> mask_image = download_image(mask_url).resize((512, 512))

>>> pipe = StableDiffusionInpaintPipeline.from_pretrained(
...     "stable-diffusion-v1-5/stable-diffusion-inpainting", torch_dtype=torch.float16
... )
>>> pipe = pipe.to("cuda")

>>> prompt = "Face of a yellow cat, high resolution, sitting on a park bench"
>>> image = pipe(prompt=prompt, image=init_image, mask_image=mask_image).images[0]
```

#### enable_attention_slicing[[diffusers.StableDiffusionInpaintPipeline.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.StableDiffusionInpaintPipeline.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.StableDiffusionInpaintPipeline.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.StableDiffusionInpaintPipeline.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.StableDiffusionInpaintPipeline.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")
```

#### load_lora_weights[[diffusers.StableDiffusionInpaintPipeline.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/main/src/diffusers/loaders/lora_pipeline.py#L148)

**パラメータ:**

pretrained_model_name_or_path_or_dict (`str` または `os.PathLike` または `dict`) : [lora_state_dict()](/docs/diffusers/main/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/main/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/main/ja/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.lora_state_dict)を参照してください。

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

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

#### save_lora_weights[[diffusers.StableDiffusionInpaintPipeline.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/main/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パラメータを保存します。

#### encode_prompt[[diffusers.StableDiffusionInpaintPipeline.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/stable_diffusion/pipeline_stable_diffusion_inpaint.py#L312)

**パラメータ:**

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.StableDiffusionInpaintPipeline.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/stable_diffusion/pipeline_stable_diffusion_inpaint.py#L823)

**パラメータ:**

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 を参照してください。

## 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 パイプライン用の出力クラスです。

