# 超分辨率

  

Stable Diffusion 超分辨率扩散模型由 [CompVis](https://github.com/CompVis)、[Stability AI](https://stability.ai/) 和 [LAION](https://laion.ai/) 的研究人员和工程师共同开发。该模型用于将输入图像的分辨率提升 4 倍。

> [!TIP]
> 请务必查看 Stable Diffusion 的 [技巧](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/v0.43.0/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py#L78)

**参数：**

vae ([AutoencoderKL](/docs/diffusers/v0.43.0/zh/api/models/autoencoderkl#diffusers.AutoencoderKL))：变分自编码器（VAE）模型，用于将图像编码为潜在表示，并从潜在表示解码回图像。

text_encoder ([CLIPTextModel](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPTextModel))：冻结的文本编码器（[clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)）。

tokenizer ([CLIPTokenizer](https://huggingface.co/docs/transformers/v5.22.2/en/model_doc/clip#transformers.CLIPTokenizer))：一个用于对文本进行分词的 `CLIPTokenizer`。

unet ([UNet2DConditionModel](/docs/diffusers/v0.43.0/zh/api/models/unet2d-cond#diffusers.UNet2DConditionModel))：一个用于对编码后的图像潜变量进行去噪的 `UNet2DConditionModel`。

low_res_scheduler ([SchedulerMixin](/docs/diffusers/v0.43.0/zh/api/schedulers/overview#diffusers.SchedulerMixin))：用于为低分辨率条件图像添加初始噪声的调度器。它必须是 [DDPMScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/ddpm#diffusers.DDPMScheduler) 的一个实例。

scheduler ([SchedulerMixin](/docs/diffusers/v0.43.0/zh/api/schedulers/overview#diffusers.SchedulerMixin))：用于与 `unet` 配合以去除编码后的图像潜变量噪声的调度器。可以是 [DDIMScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/ddim#diffusers.DDIMScheduler)、[LMSDiscreteScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler) 或 [PNDMScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/pndm#diffusers.PNDMScheduler) 之一。

使用 Stable Diffusion 2 进行文本引导图像超分辨率的 Pipeline。

该模型继承自 [DiffusionPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/overview#diffusers.DiffusionPipeline)。有关为所有流水线实现的通用方法（下载、保存、在特定设备上运行等），请参阅父类文档。

该 pipeline 还继承了以下加载方法：
- 用于加载文本反转嵌入的 [load_textual_inversion()](/docs/diffusers/v0.43.0/zh/api/loaders/textual_inversion#diffusers.loaders.TextualInversionLoaderMixin.load_textual_inversion)
- 用于加载 LoRA 权重的 [load_lora_weights()](/docs/diffusers/v0.43.0/zh/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights)
- 用于保存 LoRA 权重的 [save_lora_weights()](/docs/diffusers/v0.43.0/zh/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.save_lora_weights)
- 用于加载 `.ckpt` 文件的 [from_single_file()](/docs/diffusers/v0.43.0/zh/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file)

#### __调用__[[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/v0.43.0/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`, *可选*，默认为 20) : 添加到放大后的输入图像中的噪声量。其值必须在 `[0, max_noise_level]` 范围内，其中 `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/v0.43.0/zh/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/v0.43.0/zh/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`，*可选*，默认为 1)：`callback` 函数的调用频率。如果未指定，则回调函数会在每一步被调用。

cross_attention_kwargs (`dict`, *可选*) : 一个 kwargs 字典，如果指定，将作为 [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) 中定义的 `AttentionProcessor` 的参数传递。

clip_skip (`int`, *可选*) : 在计算提示嵌入时，从 CLIP 中跳过的层数。值为 1 表示将使用倒数第二层的输出来计算提示嵌入。

**返回：** [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) 或 `tuple`

如果 `return_dict` 为 `True`，则返回 [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput)；否则返回一个 `tuple`，其中第一个元素是包含生成图像的列表，第二个元素是 `bool` 列表，用于指示对应的生成图像是否包含“不适合工作场所”（nsfw）内容。

用于生成的 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/v0.43.0/src/diffusers/pipelines/pipeline_utils.py#L2030)

**参数：**

slice_size (`str` 或 `int`，*可选*，默认为 `"auto"`)：当值为 `"auto"` 时，将输入到注意力头的数据减半，因此注意力计算将分两步进行。如果值为 `"max"`，则每次只运行一个切片，以节省最大内存。如果提供了数字，则使用 `attention_head_dim // slice_size` 个切片。在这种情况下，`attention_head_dim` 必须是 `slice_size` 的倍数。

启用切片注意力计算。启用此选项后，注意力模块会将输入张量拆分为多个切片，分步计算注意力。当存在多个注意力头时，计算将按顺序针对每个头执行。此功能可用于节省部分内存，代价是速度略有下降。

> [!WARNING] > ⚠️ 如果你已经在使用 `scaled_dot_product_attention`（SDPA），请勿启用注意力切片
来自 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/v0.43.0/src/diffusers/pipelines/pipeline_utils.py#L2067)

禁用切片注意力计算。如果之前调用过 `enable_attention_slicing`，则注意力将一次性计算完成。

#### 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/v0.43.0/src/diffusers/pipelines/pipeline_utils.py#L1975)

**参数：**

attention_op (`Callable`，*可选*)：覆盖默认的 `None` 运算符，用作 xFormers 的 [`memory_efficient_attention()`](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.memory_efficient_attention) 函数的 `op` 参数。

启用来自 [xFormers](https://facebookresearch.github.io/xformers/) 的内存高效注意力机制。启用此选项后，您应能观察到更低的 GPU 内存占用，并可能在推理阶段获得加速。训练阶段的加速不保证。

> [!WARNING] > ⚠️ 当同时启用 memory efficient attention 和 sliced attention 时，memory efficient
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/v0.43.0/src/diffusers/pipelines/pipeline_utils.py#L2006)

禁用来自 [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/v0.43.0/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_embeds 将从 `negative_prompt` 输入参数生成。

lora_scale (`float`, *可选*) : 如果加载了 LoRA 层，将应用于文本编码器所有 LoRA 层的 LoRA 缩放系数。

clip_skip (`int`, *可选*) : 在计算提示嵌入时，从 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/v0.43.0/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]`) : 一个列表，指示对应的生成图像是否包含“不适合工作场所”（nsfw）内容；如果无法执行安全检查，则为 `None`。

Stable Diffusion 管道的输出类。

