# 超解像

  

Stable Diffusion upscaler拡散モデルは、[CompVis](https://github.com/CompVis)、[Stability AI](https://stability.ai/)、[LAION](https://laion.ai/)の研究者およびエンジニアによって作成されました。入力画像の解像度を4倍に高めるために使用されます。

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

## StableDiffusionUpscalePipeline[[diffusers.StableDiffusionUpscalePipeline]]

#### diffusers.StableDiffusionUpscalePipeline[[diffusers.StableDiffusionUpscalePipeline]]

```python
diffusers.StableDiffusionUpscalePipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet2DConditionModel, low_res_scheduler: DDPMScheduler, scheduler: KarrasDiffusionSchedulers, safety_checker: typing.Any | None = None, feature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | None = None, watermarker: typing.Any | None = None, max_noise_level: int = 350)
```

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

**パラメータ:**

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

low_res_scheduler ([SchedulerMixin](/docs/diffusers/main/ja/api/schedulers/overview#diffusers.SchedulerMixin)) : 低解像度の条件付け画像に初期ノイズを追加するために使用されるスケジューラーです。[DDPMScheduler](/docs/diffusers/main/ja/api/schedulers/ddpm#diffusers.DDPMScheduler) のインスタンスである必要があります。

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) のいずれかです。

Stable Diffusion 2 を用いたテキストガイド型画像スーパーリゾリューションのパイプライン。

このモデルは [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)

#### __call__[[diffusers.StableDiffusionUpscalePipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, num_inference_steps: int = 75, guidance_scale: float = 9.0, noise_level: int = 20, 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, output_type: str | None = 'pil', return_dict: bool = True, callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None, callback_steps: int = 1, cross_attention_kwargs: dict[str, typing.Any] | None = None, clip_skip: int = None)
```

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

**パラメータ:**

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` またはテンソル。

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

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

noise_level (`int`, *optional*, デフォルトは 20) : アップスケールされた入力画像に追加するノイズの量。`max_noise_level` はスケジューラによって定義されるため、`[0, max_noise_level]` の範囲内である必要があります。`noise_level` が大きいほど入力に多くのノイズが加わり、バリエーションは増加しますが、元の画像への忠実度は低下します。

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` 入力引数から生成されます。

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)を返すかどうか。

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

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

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の場合、プロンプト埋め込みの計算に最終レイヤーの直前のレイヤーの出力が使用されます。

**戻り値:** [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 requests
>>> from PIL import Image
>>> from io import BytesIO
>>> from diffusers import StableDiffusionUpscalePipeline
>>> import torch

>>> # load model and scheduler
>>> model_id = "stabilityai/stable-diffusion-x4-upscaler"
>>> pipeline = StableDiffusionUpscalePipeline.from_pretrained(
...     model_id, variant="fp16", torch_dtype=torch.float16
... )
>>> pipeline = pipeline.to("cuda")

>>> # let's download an  image
>>> url = "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale/low_res_cat.png"
>>> response = requests.get(url)
>>> low_res_img = Image.open(BytesIO(response.content)).convert("RGB")
>>> low_res_img = low_res_img.resize((128, 128))
>>> prompt = "a white cat"

>>> upscaled_image = pipeline(prompt=prompt, image=low_res_img).images[0]
>>> upscaled_image.save("upsampled_cat.png")
```

#### enable_attention_slicing[[diffusers.StableDiffusionUpscalePipeline.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.StableDiffusionUpscalePipeline.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.StableDiffusionUpscalePipeline.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.StableDiffusionUpscalePipeline.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/)からのメモリ効率の高いアテンションを無効にします。

#### encode_prompt[[diffusers.StableDiffusionUpscalePipeline.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_upscale.py#L217)

**パラメータ:**

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

