# Stable Diffusion XL

  
  

Stable Diffusion XL (SDXL) 由 Dustin Podell、Zion English、Kyle Lacey、Andreas Blattmann、Tim Dockhorn、Jonas Müller、Joe Penna 和 Robin Rombach 在 [SDXL: Improving Latent Diffusion Models for High-Resolution Image Synthesis](https://huggingface.co/papers/2307.01952) 中提出。

该论文的摘要如下：

*我们提出了 SDXL，一种用于文本到图像合成的潜在扩散模型。与 Stable Diffusion 的早期版本相比，SDXL 采用了规模大三倍的 UNet 主干网络：模型参数的增加主要源于更多的注意力块以及更大的交叉注意力上下文，因为 SDXL 使用了第二个文本编码器。我们设计了多种新颖的条件化方案，并在多种宽高比上训练了 SDXL。我们还引入了一个精修模型，利用事后图像到图像技术来提升 SDXL 生成样本的视觉保真度。我们证明，与 Stable Diffusion 的早期版本相比，SDXL 的性能有了显著提升，并取得了与黑盒最先进图像生成器相媲美的结果。*

## 提示

- 已知使用 SDXL 配合 DPM++ 调度器在少于 50 步的情况下会生成[视觉伪影](https://github.com/huggingface/diffusers/issues/5433)，因为求解器会出现数值不稳定。要解决此问题，请查看此[PR](https://github.com/huggingface/diffusers/pull/5541)，其中针对 ODE/SDE 求解器给出了建议：
	- 设置 `use_karras_sigmas=True` 或 `lu_lambdas=True` 以提升图像质量
	- 如果您使用的是步长均匀的求解器（DPM++2M 或 DPM++2M SDE），请设置 `euler_at_final=True`
- 大多数 SDXL 检查点在 1024x1024 的图像尺寸下效果最佳。768x768 和 512x512 的图像尺寸也受支持，但效果稍逊。不建议使用低于 512x512 的尺寸，对于 [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0) 等默认检查点，低分辨率的效果可能更差。
- SDXL 可以为每个用于训练的文本编码器传入不同的提示词。我们甚至可以将同一提示词的不同部分分别传给各个文本编码器。
- SDXL 生成的图像可以通过在图生图设置中使用精修模型（refiner model）来进一步提升质量。
- SDXL 提供 `negative_original_size`、`negative_crops_coords_top_left` 和 `negative_target_size`，用于对图像分辨率和裁剪参数进行负向条件控制。

> [!TIP]
> 请前往 [Stability AI](https://huggingface.co/stabilityai) Hub 组织，查看官方的基础模型和精修模型检查点！

请确保已安装以下库。

```py
# uncomment to install the necessary libraries in Colab
#!pip install -q diffusers transformers accelerate invisible-watermark>=0.2.0
```

> [!WARNING]
> 我们建议安装 [invisible-watermark](https://pypi.org/project/invisible-watermark/) 库，以帮助识别生成的图像。如果已安装 invisible-watermark 库，则默认会使用它。要禁用水印功能：
>
> ```py
> pipeline = StableDiffusionXLPipeline.from_pretrained(..., add_watermarker=False)
> ```

## 加载模型检查点

模型权重可能存储在 Hub 或本地的不同子文件夹中，在这种情况下，您应使用 [from_pretrained()](/docs/diffusers/v0.43.0/zh/api/pipelines/overview#diffusers.DiffusionPipeline.from_pretrained) 方法：

```py
from diffusers import StableDiffusionXLPipeline, StableDiffusionXLImg2ImgPipeline
import torch

pipeline = StableDiffusionXLPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0", dtype=torch.float16, variant="fp16", use_safetensors=True
).to("cuda")  # or "mps", "xpu", "cpu"

refiner = StableDiffusionXLImg2ImgPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-refiner-1.0", dtype=torch.float16, use_safetensors=True, variant="fp16"
).to("cuda")
```

您还可以使用 [from_single_file()](/docs/diffusers/v0.43.0/zh/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file) 方法从 Hub 或本地加载以单文件格式（`.ckpt` 或 `.safetensors`）存储的模型检查点：

```py
from diffusers import StableDiffusionXLPipeline, StableDiffusionXLImg2ImgPipeline
import torch

pipeline = StableDiffusionXLPipeline.from_single_file(
    "https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/blob/main/sd_xl_base_1.0.safetensors",
    dtype=torch.float16
).to("cuda")  # or "mps", "xpu", "cpu"

refiner = StableDiffusionXLImg2ImgPipeline.from_single_file(
    "https://huggingface.co/stabilityai/stable-diffusion-xl-refiner-1.0/blob/main/sd_xl_refiner_1.0.safetensors", dtype=torch.float16
).to("cuda")
```

## 文本到图像

对于文生图任务，请传入文本提示词。默认情况下，SDXL 会生成 1024x1024 的图像以获得最佳效果。您可以尝试将 `height` 和 `width` 参数设置为 768x768 或 512x512，但低于 512x512 的分辨率可能无法正常工作。

```py
from diffusers import AutoPipelineForText2Image
import torch

pipeline_text2image = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0", dtype=torch.float16, variant="fp16", use_safetensors=True
).to("cuda")  # or "mps", "xpu", "cpu"

prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
image = pipeline_text2image(prompt=prompt).images[0]
image
```

    

## 图像到图像

对于图像到图像的转换，SDXL 在 768x768 到 1024x1024 之间的图像尺寸下表现尤为出色。传入一张初始图像，并传入一个文本提示词以对该图像进行条件控制：

```py
from diffusers import AutoPipelineForImage2Image
from diffusers.utils import load_image, make_image_grid

# use from_pipe to avoid consuming additional memory when loading a checkpoint
pipeline = AutoPipelineForImage2Image.from_pipe(pipeline_text2image).to("cuda")  # or "mps", "xpu", "cpu"

url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/sdxl-text2img.png"
init_image = load_image(url)
prompt = "a dog catching a frisbee in the jungle"
image = pipeline(prompt, image=init_image, strength=0.8, guidance_scale=10.5).images[0]
make_image_grid([init_image, image], rows=1, cols=2)
```

    

## 图像修复

对于图像修复（inpainting），你需要原始图像以及一个掩码（mask），用于指定原始图像中要替换的区域。创建一个提示词（prompt），描述你希望用何种内容替换被掩码覆盖的区域。

```py
from diffusers import AutoPipelineForInpainting
from diffusers.utils import load_image, make_image_grid

# use from_pipe to avoid consuming additional memory when loading a checkpoint
pipeline = AutoPipelineForInpainting.from_pipe(pipeline_text2image).to("cuda")  # or "mps", "xpu", "cpu"

img_url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/sdxl-text2img.png"
mask_url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/sdxl-inpaint-mask.png"

init_image = load_image(img_url)
mask_image = load_image(mask_url)

prompt = "A deep sea diver floating"
image = pipeline(prompt=prompt, image=init_image, mask_image=mask_image, strength=0.85, guidance_scale=12.5).images[0]
make_image_grid([init_image, mask_image, image], rows=1, cols=3)
```

    

## 提升图像质量

SDXL 包含一个专门用于对低噪声阶段图像进行去噪的 [refiner model](https://huggingface.co/stabilityai/stable-diffusion-xl-refiner-1.0)，以从基础模型生成更高质量的图像。使用 refiner 有两种方式：

1. 将基础模型和精修模型结合使用，以生成精修后的图像
2. 使用基础模型生成图像，然后使用精修模型为图像添加更多细节（这正是 SDXL 最初的训练方式）

### 基础 + 精修模型

当您将基础模型和精修模型一起用于生成图像时，这被称为[*专家去噪器集成*](https://research.nvidia.com/labs/dir/eDiff-I/)。与将基础模型的输出传递给精修模型相比，专家去噪器集成方法所需的总去噪步骤更少，因此运行速度应显著更快。但是，由于基础模型的输出仍包含大量噪声，您将无法检查该输出。

作为一组专家去噪器，基础模型在高噪声扩散阶段充当专家，而精修模型在低噪声扩散阶段充当专家。加载基础和精修模型：

```py
from diffusers import DiffusionPipeline
import torch

base = DiffusionPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0", dtype=torch.float16, variant="fp16", use_safetensors=True
).to("cuda")  # or "mps", "xpu", "cpu"

refiner = DiffusionPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-refiner-1.0",
    text_encoder_2=base.text_encoder_2,
    vae=base.vae,
    dtype=torch.float16,
    use_safetensors=True,
    variant="fp16",
).to("cuda")
```

要使用此方法，你需要为每个模型定义其各自阶段所需的时间步数。对于基础模型，这由 [`denoising_end`](https://huggingface.co/docs/diffusers/main/en/api/pipelines/stable_diffusion/stable_diffusion_xl#diffusers.StableDiffusionXLPipeline.__call__.denoising_end) 参数控制；对于 refiner 模型，则由 [`denoising_start`](https://huggingface.co/docs/diffusers/main/en/api/pipelines/stable_diffusion/stable_diffusion_xl#diffusers.StableDiffusionXLImg2ImgPipeline.__call__.denoising_start) 参数控制。

> [!TIP]
> `denoising_end` 和 `denoising_start` 参数应为 0 到 1 之间的浮点数。这些参数表示为调度器所定义的离散时间步的比例。如果您同时使用了 `strength` 参数，它将被忽略，因为去噪步数由模型训练所用的离散时间步和声明的小数截止值决定。

让我们将 `denoising_end=0.8` 设置为 0.8，以便基础模型执行前 80% 的去噪过程，即处理 **高噪声** 时间步；并将 `denoising_start=0.8` 设置为 0.8，以便精修模型执行后 20% 的去噪过程，即处理 **低噪声** 时间步。基础模型的输出应为 **潜在** 空间中的表示，而不是 PIL 图像。

```py
prompt = "A majestic lion jumping from a big stone at night"

image = base(
    prompt=prompt,
    num_inference_steps=40,
    denoising_end=0.8,
    output_type="latent",
).images
image = refiner(
    prompt=prompt,
    num_inference_steps=40,
    denoising_start=0.8,
    image=image,
).images[0]
image
```

  
    
    默认基础模型
  
  
    
    专家去噪器集成
  

refiner 模型也可以用于 [StableDiffusionXLInpaintPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/stable_diffusion/stable_diffusion_xl#diffusers.StableDiffusionXLInpaintPipeline) 中的图像修复：

```py
from diffusers import StableDiffusionXLInpaintPipeline
from diffusers.utils import load_image, make_image_grid
import torch

base = StableDiffusionXLInpaintPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0", dtype=torch.float16, variant="fp16", use_safetensors=True
).to("cuda")  # or "mps", "xpu", "cpu"

refiner = StableDiffusionXLInpaintPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-refiner-1.0",
    text_encoder_2=base.text_encoder_2,
    vae=base.vae,
    dtype=torch.float16,
    use_safetensors=True,
    variant="fp16",
).to("cuda")

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 = load_image(img_url)
mask_image = load_image(mask_url)

prompt = "A majestic tiger sitting on a bench"
num_inference_steps = 75
high_noise_frac = 0.7

image = base(
    prompt=prompt,
    image=init_image,
    mask_image=mask_image,
    num_inference_steps=num_inference_steps,
    denoising_end=high_noise_frac,
    output_type="latent",
).images
image = refiner(
    prompt=prompt,
    image=image,
    mask_image=mask_image,
    num_inference_steps=num_inference_steps,
    denoising_start=high_noise_frac,
).images[0]
make_image_grid([init_image, mask_image, image.resize((512, 512))], rows=1, cols=3)
```

这种由多个专家去噪器组成的集成方法在所有可用的调度器上都能很好地工作！

### 基础模型到精调模型

SDXL 通过在图像到图像的设置中，使用 refiner 模型为 base 模型生成的完全去噪图像添加额外的高质量细节，从而提升图像质量。

加载基础模型和精修模型：

```py
from diffusers import DiffusionPipeline
import torch

base = DiffusionPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0", dtype=torch.float16, variant="fp16", use_safetensors=True
).to("cuda")  # or "mps", "xpu", "cpu"

refiner = DiffusionPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-refiner-1.0",
    text_encoder_2=base.text_encoder_2,
    vae=base.vae,
    dtype=torch.float16,
    use_safetensors=True,
    variant="fp16",
).to("cuda")
```

> [!WARNING]
> 您可以将 SDXL refiner 与不同的基础模型配合使用。例如，您可以使用 [Hunyuan-DiT](../hunyuandit) 或 [PixArt-Sigma](../pixart_sigma) 流水线来生成对提示词遵循度更高的图像。生成图像后，您可以将其传入 SDXL refiner 模型，以提升最终生成质量。

从基础模型生成图像，并将模型输出设置为 **latent** 空间：

```py
prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"

image = base(prompt=prompt, output_type="latent").images[0]
```

将生成的图像传递给 refiner 模型：

```py
image = refiner(prompt=prompt, image=image[None, :]).images[0]
```

  
    
    基础模型
  
  
    
    基础模型 + 精修模型
  

对于图像修复，请在 [StableDiffusionXLInpaintPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/stable_diffusion/stable_diffusion_xl#diffusers.StableDiffusionXLInpaintPipeline) 中加载基础模型和精修模型，移除 `denoising_end` 和 `denoising_start` 参数，并为精修模型选择较少的推理步数。

## 微条件

SDXL 的训练涉及多种额外的条件化技术，这些技术被称为*微条件化*。其中包括原始图像尺寸、目标图像尺寸以及裁剪参数。在推理阶段，可以利用这些微条件化来生成高质量且居中的图像。

> [!TIP]
> 借助 classifier-free guidance，你可以同时使用 micro-conditioning 和 negative micro-conditioning 参数。这些参数在 [StableDiffusionXLPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/stable_diffusion/stable_diffusion_xl#diffusers.StableDiffusionXLPipeline)、[StableDiffusionXLImg2ImgPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/stable_diffusion/stable_diffusion_xl#diffusers.StableDiffusionXLImg2ImgPipeline)、[StableDiffusionXLInpaintPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/stable_diffusion/stable_diffusion_xl#diffusers.StableDiffusionXLInpaintPipeline) 和 [StableDiffusionXLControlNetPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/controlnet_sdxl#diffusers.StableDiffusionXLControlNetPipeline) 中可用。

### 尺寸条件

有两种尺寸条件类型：

- [`original_size`](https://huggingface.co/docs/diffusers/main/en/api/pipelines/stable_diffusion/stable_diffusion_xl#diffusers.StableDiffusionXLPipeline.__call__.original_size) 条件信息来自训练批次中的放大图像（因为丢弃占训练数据总量近 40% 的较小图像会造成浪费）。通过这种方式，SDXL 学习到高分辨率图像中不应存在放大伪影。在推理阶段，你可以使用 `original_size` 来指示原始图像的分辨率。使用默认值 `(1024, 1024)` 会生成更高质量的图像，使其类似于数据集中的 1024x1024 图像。如果你选择使用较低的分辨率，例如 `(256, 256)`，模型仍然会生成 1024x1024 的图像，但它们的视觉效果会类似于数据集中的低分辨率图像（图案更简单、存在模糊）。

- [`target_size`](https://huggingface.co/docs/diffusers/main/en/api/pipelines/stable_diffusion/stable_diffusion_xl#diffusers.StableDiffusionXLPipeline.__call__.target_size) 条件源自对 SDXL 的微调，以支持不同的图像宽高比。在推理过程中，如果使用 `(1024, 1024)` 作为默认值，生成的图像将类似于数据集中方形图像的构图。我们建议将 `target_size` 和 `original_size` 设置为相同的值，但您也可以自由尝试其他选项！

🤗 Diffusers 还允许你指定关于图像尺寸的负面条件，以引导生成过程避开某些图像分辨率：

```py
from diffusers import StableDiffusionXLPipeline
import torch

pipe = StableDiffusionXLPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0", dtype=torch.float16, variant="fp16", use_safetensors=True
).to("cuda")  # or "mps", "xpu", "cpu"

prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
image = pipe(
    prompt=prompt,
    negative_original_size=(512, 512),
    negative_target_size=(1024, 1024),
).images[0]
```

  
  以 (128, 128)、(256, 256) 和 (512, 512) 图像分辨率为负条件生成的图像。

### 裁剪条件

由早期 Stable Diffusion 模型生成的图像有时看起来像是被裁剪过的。这是因为在训练过程中，图像实际上会被裁剪，以确保同一批次中的所有图像尺寸一致。通过以裁剪坐标作为条件，SDXL *学习*到未进行裁剪——坐标为 `(0, 0)`——通常与居中的主体和完整的面部相关联（这也是 🤗 Diffusers 中的默认值）。如果您想生成非居中的构图，可以尝试使用不同的坐标！

```py
from diffusers import StableDiffusionXLPipeline
import torch

pipeline = StableDiffusionXLPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0", dtype=torch.float16, variant="fp16", use_safetensors=True
).to("cuda")  # or "mps", "xpu", "cpu"

prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
image = pipeline(prompt=prompt, crops_coords_top_left=(256, 0)).images[0]
image
```

    

您还可以通过指定负裁剪坐标，将生成过程引导至远离某些裁剪参数：

```py
from diffusers import StableDiffusionXLPipeline
import torch

pipe = StableDiffusionXLPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0", dtype=torch.float16, variant="fp16", use_safetensors=True
).to("cuda")  # or "mps", "xpu", "cpu"

prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
image = pipe(
    prompt=prompt,
    negative_original_size=(512, 512),
    negative_crops_coords_top_left=(0, 0),
    negative_target_size=(1024, 1024),
).images[0]
image
```

## 为每个 text-encoder 使用不同的 prompt

SDXL 使用两个文本编码器，因此可以为每个文本编码器传入不同的提示词，从而[提升生成质量](https://github.com/huggingface/diffusers/issues/4004#issuecomment-1627764201)。请将原始提示词传入 `prompt`，将第二个提示词传入 `prompt_2`（如果使用负面提示词，请分别使用 `negative_prompt` 和 `negative_prompt_2`）：

```py
from diffusers import StableDiffusionXLPipeline
import torch

pipeline = StableDiffusionXLPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0", dtype=torch.float16, variant="fp16", use_safetensors=True
).to("cuda")  # or "mps", "xpu", "cpu"

# prompt is passed to OAI CLIP-ViT/L-14
prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
# prompt_2 is passed to OpenCLIP-ViT/bigG-14
prompt_2 = "Van Gogh painting"
image = pipeline(prompt=prompt, prompt_2=prompt_2).images[0]
image
```

    

双文本编码器还支持文本反转嵌入，这些嵌入需要单独加载，具体说明请参见[文本反转](../../../using-diffusers/legacy_adapters#textual-inversion)指南。

## 优化

SDXL 是一个大型模型，您可能需要优化内存才能使其在您的硬件上运行。以下是一些节省内存并加快推理速度的技巧。

1. 使用 [enable_model_cpu_offload()](/docs/diffusers/v0.43.0/zh/api/pipelines/overview#diffusers.DiffusionPipeline.enable_model_cpu_offload) 将模型卸载到 CPU，以解决内存不足错误：

```diff
- base.to("cuda")  # or "mps", "xpu", "cpu"
- refiner.to("cuda")
+ base.enable_model_cpu_offload()
+ refiner.enable_model_cpu_offload()
```

2. 使用 `torch.compile` 可获得约 20% 的速度提升（需要 `torch>=2.0`）：

```diff
+ base.unet = torch.compile(base.unet, mode="reduce-overhead", fullgraph=True)
+ refiner.unet = torch.compile(refiner.unet, mode="reduce-overhead", fullgraph=True)
```

3. 如果 `torch<2.0`，请启用 [xFormers](../../../optimization/attention_backends) 以运行 SDXL：

```diff
+ base.enable_xformers_memory_efficient_attention()
+ refiner.enable_xformers_memory_efficient_attention()
```

## 资源

如果您对实验 SDXL 中使用的 [UNet2DConditionModel](/docs/diffusers/v0.43.0/zh/api/models/unet2d-cond#diffusers.UNet2DConditionModel) 的极简版本感兴趣，可以查看 [minSDXL](https://github.com/cloneofsimo/minSDXL) 实现，它使用 PyTorch 编写，并可直接与 🤗 Diffusers 兼容。

## StableDiffusionXLPipeline[[diffusers.StableDiffusionXLPipeline]]

#### diffusers.StableDiffusionXLPipeline[[diffusers.StableDiffusionXLPipeline]]

```python
diffusers.StableDiffusionXLPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, text_encoder_2: CLIPTextModelWithProjection, tokenizer: CLIPTokenizer, tokenizer_2: CLIPTokenizer, unet: UNet2DConditionModel, scheduler: KarrasDiffusionSchedulers, image_encoder: CLIPVisionModelWithProjection = None, feature_extractor: CLIPImageProcessorPil = None, force_zeros_for_empty_prompt: bool = True, add_watermarker: bool | None = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py#L170)

**参数：**

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

text_encoder (`CLIPTextModel`)：冻结的文本编码器。Stable Diffusion XL 使用 [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel) 的文本部分，具体为 [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) 变体。

text_encoder_2 (` CLIPTextModelWithProjection`)：第二个冻结的文本编码器。Stable Diffusion XL 使用 [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection) 的文本和池化部分，具体为 [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k) 变体。

tokenizer (`CLIPTokenizer`)：[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer) 类的分词器。

tokenizer_2 (`CLIPTokenizer`)：第二个 [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer) 类的 Tokenizer。

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

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) 之一。

force_zeros_for_empty_prompt (`bool`，*可选*，默认为 `"True"`)：是否强制将负提示嵌入始终设置为 0。另请参阅 `stabilityai/stable-diffusion-xl-base-1-0` 的配置。

add_watermarker (`bool`，*可选*)：是否使用 [invisible_watermark 库](https://github.com/ShieldMnt/invisible-watermark/) 为输出图像添加水印。如果未定义，则当该包已安装时默认为 True，否则不使用水印。

使用 Stable Diffusion XL 进行文本到图像生成的 Pipeline。

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

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

#### __调用__[[diffusers.StableDiffusionXLPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, prompt_2: str | list[str] | None = None, height: int | None = None, width: int | None = None, num_inference_steps: int = 50, timesteps: list[int] = None, sigmas: list[float] = None, denoising_end: float | None = None, guidance_scale: float = 5.0, negative_prompt: str | list[str] | None = None, negative_prompt_2: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, 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, guidance_rescale: float = 0.0, original_size: tuple[int, int] | None = None, crops_coords_top_left: tuple[int, int] = (0, 0), target_size: tuple[int, int] | None = None, negative_original_size: tuple[int, int] | None = None, negative_crops_coords_top_left: tuple[int, int] = (0, 0), negative_target_size: tuple[int, int] | None = None, 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[str] = ['latents'], **kwargs)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py#L823)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的提示词或提示词列表。如果未定义，则必须改为传入 `prompt_embeds`。

prompt_2 (`str` 或 `list[str]`，*可选*)：要发送给 `tokenizer_2` 和 `text_encoder_2` 的提示词或提示词列表。如果未定义，则两个文本编码器均使用 `prompt`。

height (`int`，*可选*，默认为 self.unet.config.sample_size * self.vae_scale_factor)：生成图像的高度（以像素为单位）。默认设置为 1024 以获得最佳效果。对于 [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0) 以及未在低分辨率上专门微调的检查点，低于 512 像素的效果不佳。

width (`int`，*可选*，默认为 self.unet.config.sample_size * self.vae_scale_factor)：生成图像的像素宽度。默认设置为 1024 以获得最佳效果。对于 [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0) 以及未在低分辨率上专门微调的检查点，低于 512 像素的宽度效果不佳。

num_inference_steps (`int`, *可选*，默认为 50)：去噪步数。更多的去噪步数通常能带来更高质量的图像，但代价是推理速度变慢。

timesteps (`list[int]`，*可选*)：用于在支持 `set_timesteps` 方法中 `timesteps` 参数的调度器中，指定去噪过程所使用的自定义时间步。如果未定义，则使用传入 `num_inference_steps` 时的默认行为。必须按降序排列。

sigmas (`list[float]`, *可选*) : 用于支持在 `set_timesteps` 方法中接受 `sigmas` 参数的调度器的去噪过程的自定义 sigmas。如果未定义，将使用传入 `num_inference_steps` 时的默认行为。

denoising_end (`float`, *可选*) : 指定时，确定在有意提前终止之前，总去噪过程需要完成的比例（介于 0.0 和 1.0 之间）。因此，返回的样本仍将保留相当多的噪声，具体程度由调度器选择的离散时间步决定。当此管道作为“去噪器混合”多管道设置的一部分时，应理想地使用 denoising_end 参数，如 [**优化图像输出**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output) 中所述。

guidance_scale (`float`，*可选*，默认值为 5.0)：如[Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598)中定义的引导尺度。`guidance_scale` 定义为[Imagen Paper](https://huggingface.co/papers/2205.11487)中公式 2 的 `w`。通过设置 `guidance_scale > 1` 来启用引导尺度。较高的引导尺度会促使生成与文本 `prompt` 紧密关联的图像，但通常以牺牲图像质量为代价。

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的负面提示词。如果未定义，则必须传入 `negative_prompt_embeds`。当不使用引导时（即 `guidance_scale` 小于 `1` 时），此参数将被忽略。

negative_prompt_2 (`str` 或 `list[str]`，*可选*)：要发送给 `tokenizer_2` 和 `text_encoder_2` 的提示词或提示词列表，用于引导图像生成。如果未定义，则两个文本编码器都会使用 `negative_prompt`。

num_images_per_prompt (`int`，*可选*，默认为 1)：每个提示词生成的图像数量。

eta (`float`，*可选*，默认值为 0.0)：对应 DDIM 论文中的参数 eta (η)：https://huggingface.co/papers/2010.02502。仅适用于 [schedulers.DDIMScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/ddim#diffusers.DDIMScheduler)，对其他调度器将被忽略。

generator (`torch.Generator` 或 `list[torch.Generator]`，*可选*)：一个或一组 [torch 生成器](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` 输入参数生成。

pooled_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的池化文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，将从 `prompt` 输入参数生成池化文本嵌入。

negative_pooled_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的负向池化文本嵌入。可用于轻松调整文本输入，*例如* 提示词权重。如果未提供，将从 `negative_prompt` 输入参数生成 pooled negative_prompt_embeds。

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](https://pillow.readthedocs.io/en/stable/)：`PIL.Image.Image` 或 `np.array`。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 `~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput` 而不是普通元组。

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

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

original_size (`tuple[int]`，*可选*，默认为 (1024, 1024))：如果 `original_size` 与 `target_size` 不同，图像将看起来像是被下采样或上采样了。如果未指定，`original_size` 默认为 `(height, width)`。这是 SDXL 微条件的一部分，如 [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952) 第 2.2 节所述。

crops_coords_top_left (`tuple[int]`，*可选*，默认值为 (0, 0))：`crops_coords_top_left` 可用于生成一张看似从 `crops_coords_top_left` 位置向下裁剪的图像。通常将 `crops_coords_top_left` 设置为 (0, 0) 即可获得构图良好、居中效果佳的图像。这是 SDXL 微条件的一部分，详见 [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952) 中的第 2.2 节。

target_size (`tuple[int]`，*可选*，默认值为 (1024, 1024))：在大多数情况下，应将 `target_size` 设置为生成图像所需的宽度和高度。如果未指定，则默认为 `(height, width)`。这是 [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952) 第 2.2 节中所述 SDXL 微条件化的一部分。

negative_original_size (`tuple[int]`，*可选*，默认为 (1024, 1024))：用于基于特定的图像分辨率对生成过程进行负向条件控制。这是 SDXL 微条件化的一部分，如 [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952) 第 2.2 节所述。更多信息请参阅此 issue 讨论：https://github.com/huggingface/diffusers/issues/4208。

negative_crops_coords_top_left (`tuple[int]`，*可选*，默认值为 (0, 0))：用于根据特定的裁剪坐标对生成过程施加负向条件。这是 SDXL 微条件的一部分，详见 [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952) 中的第 2.2 节。更多信息请参阅此 issue 讨论：https://github.com/huggingface/diffusers/issues/4208。

negative_target_size (`tuple[int]`，*可选*，默认值为 (1024, 1024))：用于根据目标图像分辨率对生成过程施加负向条件。在大多数情况下，它应与 `target_size` 相同。这是 SDXL 微条件的一部分，如 [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952) 第 2.2 节所述。更多信息，请参阅此 issue 讨论：https://github.com/huggingface/diffusers/issues/4208。

clip_skip (`int`, *可选*) : 在计算提示嵌入时，从 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` 属性中列出的变量。

**返回：** `~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput` 或 `tuple`

如果 `return_dict` 为 True，则返回 `~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`，否则返回 `tuple`。当返回元组时，第一个元素是一个包含生成图像的列表。

调用生成 pipeline 时调用的函数。

示例：
```py
>>> import torch
>>> from diffusers import StableDiffusionXLPipeline

>>> pipe = StableDiffusionXLPipeline.from_pretrained(
...     "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
... )
>>> pipe = pipe.to("cuda")

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

#### encode_prompt[[diffusers.StableDiffusionXLPipeline.encode_prompt]]

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

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py#L283)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：要编码的提示

prompt_2 (`str` 或 `list[str]`，*可选*)：要发送给 `tokenizer_2` 和 `text_encoder_2` 的提示词或提示词列表。如果未定义，则两个文本编码器均使用 `prompt`。

device : (`torch.device`): torch 设备

num_images_per_prompt (`int`) : 每个提示词应生成的图像数量

do_classifier_free_guidance (`bool`) : 是否使用 classifier free guidance

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的负面提示词。如果未定义，则必须传入 `negative_prompt_embeds`。当不使用引导时（即 `guidance_scale` 小于 `1` 时），此参数将被忽略。

negative_prompt_2 (`str` 或 `list[str]`，*可选*)：要发送给 `tokenizer_2` 和 `text_encoder_2` 的提示词或提示词列表，用于引导图像生成。如果未定义，则两个文本编码器都会使用 `negative_prompt`。

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，文本嵌入将从 `prompt` 输入参数生成。

negative_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的负向文本嵌入。可用于轻松调整文本输入，*例如* 提示词权重。如果未提供，negative_prompt_embeds 将从 `negative_prompt` 输入参数生成。

pooled_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的池化文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，将从 `prompt` 输入参数生成池化文本嵌入。

negative_pooled_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的负向池化文本嵌入。可用于轻松调整文本输入，*例如* 提示词权重。如果未提供，将从 `negative_prompt` 输入参数生成 pooled negative_prompt_embeds。

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

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

将提示词编码为文本编码器的隐藏状态。

#### get_guidance_scale_embedding[[diffusers.StableDiffusionXLPipeline.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/v0.43.0/src/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py#L758)

**参数：**

w (`torch.Tensor`) : 生成具有指定 guidance scale 的嵌入向量，以用于后续丰富时间步嵌入。

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

## StableDiffusionXLImg2ImgPipeline[[diffusers.StableDiffusionXLImg2ImgPipeline]]

#### diffusers.StableDiffusionXLImg2ImgPipeline[[diffusers.StableDiffusionXLImg2ImgPipeline]]

```python
diffusers.StableDiffusionXLImg2ImgPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, text_encoder_2: CLIPTextModelWithProjection, tokenizer: CLIPTokenizer, tokenizer_2: CLIPTokenizer, unet: UNet2DConditionModel, scheduler: KarrasDiffusionSchedulers, image_encoder: CLIPVisionModelWithProjection = None, feature_extractor: CLIPImageProcessorPil = None, requires_aesthetics_score: bool = False, force_zeros_for_empty_prompt: bool = True, add_watermarker: bool | None = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py#L188)

**参数：**

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

text_encoder (`CLIPTextModel`)：冻结的文本编码器。Stable Diffusion XL 使用 [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel) 的文本部分，具体为 [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) 变体。

text_encoder_2 (` CLIPTextModelWithProjection`)：第二个冻结的文本编码器。Stable Diffusion XL 使用 [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection) 的文本和池化部分，具体为 [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k) 变体。

tokenizer (`CLIPTokenizer`)：[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer) 类的分词器。

tokenizer_2 (`CLIPTokenizer`)：第二个 [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer) 类的 Tokenizer。

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

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) 之一。

requires_aesthetics_score (`bool`，*可选*，默认为 `"False"`)：指示 `unet` 在推理时是否需要传入 `aesthetic_score` 条件。另请参阅 `stabilityai/stable-diffusion-xl-refiner-1-0` 的配置。

force_zeros_for_empty_prompt (`bool`，*可选*，默认为 `"True"`)：是否强制将负提示嵌入始终设置为 0。另请参阅 `stabilityai/stable-diffusion-xl-base-1-0` 的配置。

add_watermarker (`bool`，*可选*)：是否使用 [invisible_watermark 库](https://github.com/ShieldMnt/invisible-watermark/) 为输出图像添加水印。如果未定义，则当该包已安装时默认为 True，否则不使用水印。

使用 Stable Diffusion XL 进行文本到图像生成的 Pipeline。

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

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

#### __调用__[[diffusers.StableDiffusionXLImg2ImgPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, prompt_2: str | list[str] | None = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, strength: float = 0.3, num_inference_steps: int = 50, timesteps: list[int] = None, sigmas: list[float] = None, denoising_start: float | None = None, denoising_end: float | None = None, guidance_scale: float = 5.0, negative_prompt: str | list[str] | None = None, negative_prompt_2: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, 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, guidance_rescale: float = 0.0, original_size: tuple[int, int] = None, crops_coords_top_left: tuple[int, int] = (0, 0), target_size: tuple[int, int] = None, negative_original_size: tuple[int, int] | None = None, negative_crops_coords_top_left: tuple[int, int] = (0, 0), negative_target_size: tuple[int, int] | None = None, aesthetic_score: float = 6.0, negative_aesthetic_score: float = 2.5, 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[str] = ['latents'], **kwargs)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py#L975)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的提示词或提示词列表。如果未定义，则必须改为传入 `prompt_embeds`。

prompt_2 (`str` 或 `list[str]`，*可选*)：要发送给 `tokenizer_2` 和 `text_encoder_2` 的提示词或提示词列表。如果未定义，则两个文本编码器均使用 `prompt`。

image (`torch.Tensor` 或 `PIL.Image.Image` 或 `np.ndarray` 或 `list[torch.Tensor]` 或 `list[PIL.Image.Image]` 或 `list[np.ndarray]`)：要使用 pipeline 修改的图像。

strength (`float`, *可选*，默认为 0.3)：从概念上讲，表示对参考 `image` 进行多大程度的变换。取值必须在 0 到 1 之间。`image` 将作为起点，`strength` 越大，添加的噪声越多。去噪步数取决于初始添加的噪声量。当 `strength` 为 1 时，添加的噪声达到最大值，去噪过程将运行 `num_inference_steps` 中指定的完整迭代次数。因此，值为 1 时实际上会忽略 `image`。请注意，如果 `denoising_start` 被声明为整数，则 `strength` 的值将被忽略。

num_inference_steps (`int`, *可选*，默认为 50)：去噪步数。更多的去噪步数通常能带来更高质量的图像，但代价是推理速度变慢。

timesteps (`list[int]`，*可选*)：用于在支持 `set_timesteps` 方法中 `timesteps` 参数的调度器中，指定去噪过程所使用的自定义时间步。如果未定义，则使用传入 `num_inference_steps` 时的默认行为。必须按降序排列。

sigmas (`list[float]`, *可选*) : 用于支持在 `set_timesteps` 方法中接受 `sigmas` 参数的调度器的去噪过程的自定义 sigmas。如果未定义，将使用传入 `num_inference_steps` 时的默认行为。

denoising_start (`float`, *可选*) : 指定时，表示在去噪过程启动前需要跳过的总去噪过程的比例（介于 0.0 和 1.0 之间）。因此，去噪过程的初始部分将被跳过，并假定传入的 `image` 是一张部分去噪的图像。请注意，当指定此参数时，strength 将被忽略。`denoising_start` 参数在将此管道集成到“去噪器混合”多管道设置中时特别有用，详见 [**提升图像质量**](https://huggingface.co/docs/diffusers/using-diffusers/sdxl#refine-image-quality)。

denoising_end (`float`, *可选*) : 指定后，用于确定在有意提前终止之前，总去噪过程需要完成的比例（介于 0.0 和 1.0 之间）。因此，返回的样本仍将保留大量噪声（大约还需要最后 20% 的时间步），并且应由一个将 `denoising_start` 设置为 0.8 的后续流水线进行去噪，使其仅对调度器的最后 20% 进行去噪。理想情况下，当此流水线作为“去噪器混合”多流水线设置的一部分时，应使用 denoising_end 参数，如 [**提升图像质量**](https://huggingface.co/docs/diffusers/using-diffusers/sdxl#refine-image-quality) 中所述。

guidance_scale (`float`，*可选*，默认值为 7.5)：如[Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598)中定义的引导尺度。`guidance_scale` 定义为[Imagen Paper](https://huggingface.co/papers/2205.11487)中公式 2 的 `w`。通过设置 `guidance_scale > 1` 来启用引导尺度。较高的引导尺度会促使生成与文本 `prompt` 紧密关联的图像，但通常以牺牲图像质量为代价。

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的负面提示词。如果未定义，则必须传入 `negative_prompt_embeds`。当不使用引导时（即 `guidance_scale` 小于 `1` 时），此参数将被忽略。

negative_prompt_2 (`str` 或 `list[str]`，*可选*)：要发送给 `tokenizer_2` 和 `text_encoder_2` 的提示词或提示词列表，用于引导图像生成。如果未定义，则两个文本编码器都会使用 `negative_prompt`。

num_images_per_prompt (`int`，*可选*，默认为 1)：每个提示词生成的图像数量。

eta (`float`，*可选*，默认值为 0.0)：对应 DDIM 论文中的参数 eta (η)：https://huggingface.co/papers/2010.02502。仅适用于 [schedulers.DDIMScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/ddim#diffusers.DDIMScheduler)，对其他调度器将被忽略。

generator (`torch.Generator` 或 `list[torch.Generator]`，*可选*)：一个或一组 [torch 生成器](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` 输入参数生成。

pooled_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的池化文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，将从 `prompt` 输入参数生成池化文本嵌入。

negative_pooled_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的负向池化文本嵌入。可用于轻松调整文本输入，*例如* 提示词权重。如果未提供，将从 `negative_prompt` 输入参数生成 pooled negative_prompt_embeds。

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](https://pillow.readthedocs.io/en/stable/)：`PIL.Image.Image` 或 `np.array`。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 `~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput` 而不是普通元组。

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

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

original_size (`tuple[int]`，*可选*，默认为 (1024, 1024))：如果 `original_size` 与 `target_size` 不同，图像将看起来像是被下采样或上采样了。如果未指定，`original_size` 默认为 `(height, width)`。这是 SDXL 微条件的一部分，如 [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952) 第 2.2 节所述。

crops_coords_top_left (`tuple[int]`，*可选*，默认值为 (0, 0))：`crops_coords_top_left` 可用于生成一张看似从 `crops_coords_top_left` 位置向下裁剪的图像。通常将 `crops_coords_top_left` 设置为 (0, 0) 即可获得构图良好、居中效果佳的图像。这是 SDXL 微条件的一部分，详见 [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952) 中的第 2.2 节。

target_size (`tuple[int]`，*可选*，默认值为 (1024, 1024))：在大多数情况下，应将 `target_size` 设置为生成图像所需的宽度和高度。如果未指定，则默认为 `(height, width)`。这是 [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952) 第 2.2 节中所述 SDXL 微条件化的一部分。

negative_original_size (`tuple[int]`，*可选*，默认为 (1024, 1024))：用于基于特定的图像分辨率对生成过程进行负向条件控制。这是 SDXL 微条件化的一部分，如 [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952) 第 2.2 节所述。更多信息请参阅此 issue 讨论：https://github.com/huggingface/diffusers/issues/4208。

negative_crops_coords_top_left (`tuple[int]`，*可选*，默认值为 (0, 0))：用于根据特定的裁剪坐标对生成过程施加负向条件。这是 SDXL 微条件的一部分，详见 [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952) 中的第 2.2 节。更多信息请参阅此 issue 讨论：https://github.com/huggingface/diffusers/issues/4208。

negative_target_size (`tuple[int]`，*可选*，默认值为 (1024, 1024))：用于根据目标图像分辨率对生成过程施加负向条件。在大多数情况下，它应与 `target_size` 相同。这是 SDXL 微条件的一部分，如 [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952) 第 2.2 节所述。更多信息，请参阅此 issue 讨论：https://github.com/huggingface/diffusers/issues/4208。

aesthetic_score (`float`，*可选*，默认值为 6.0)：用于通过影响正向文本条件来模拟生成图像的美学评分。这是 SDXL 微条件化的一部分，详见 [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952) 中的第 2.2 节。

negative_aesthetic_score (`float`，*可选*，默认值为 2.5)：[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952) 第 2.2 节中所述的 SDXL 微条件（micro-conditioning）的一部分。可通过影响负向文本条件来模拟生成图像的美学评分。

clip_skip (`int`, *可选*) : 在计算提示嵌入时，从 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` 属性中列出的变量。

**返回：** `~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput` 或 `tuple`

如果 `return_dict` 为 True，则返回 `~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`，否则返回一个 `tuple。当返回元组时，第一个元素是一个包含生成图像的列表。

调用生成 pipeline 时调用的函数。

示例：
```py
>>> import torch
>>> from diffusers import StableDiffusionXLImg2ImgPipeline
>>> from diffusers.utils import load_image

>>> pipe = StableDiffusionXLImg2ImgPipeline.from_pretrained(
...     "stabilityai/stable-diffusion-xl-refiner-1.0", torch_dtype=torch.float16
... )
>>> pipe = pipe.to("cuda")
>>> url = "https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/aa_xl/000000009.png"

>>> init_image = load_image(url).convert("RGB")
>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> image = pipe(prompt, image=init_image).images[0]
```

#### encode_prompt[[diffusers.StableDiffusionXLImg2ImgPipeline.encode_prompt]]

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

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py#L301)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：要编码的提示

prompt_2 (`str` 或 `list[str]`，*可选*)：要发送给 `tokenizer_2` 和 `text_encoder_2` 的提示词或提示词列表。如果未定义，则两个文本编码器均使用 `prompt`。

device : (`torch.device`): torch 设备

num_images_per_prompt (`int`) : 每个提示词应生成的图像数量

do_classifier_free_guidance (`bool`) : 是否使用 classifier free guidance

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的负面提示词。如果未定义，则必须传入 `negative_prompt_embeds`。当不使用引导时（即 `guidance_scale` 小于 `1` 时），此参数将被忽略。

negative_prompt_2 (`str` 或 `list[str]`，*可选*)：要发送给 `tokenizer_2` 和 `text_encoder_2` 的提示词或提示词列表，用于引导图像生成。如果未定义，则两个文本编码器都会使用 `negative_prompt`。

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，文本嵌入将从 `prompt` 输入参数生成。

negative_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的负向文本嵌入。可用于轻松调整文本输入，*例如* 提示词权重。如果未提供，negative_prompt_embeds 将从 `negative_prompt` 输入参数生成。

pooled_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的池化文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，将从 `prompt` 输入参数生成池化文本嵌入。

negative_pooled_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的负向池化文本嵌入。可用于轻松调整文本输入，*例如* 提示词权重。如果未提供，将从 `negative_prompt` 输入参数生成 pooled negative_prompt_embeds。

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

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

将提示词编码为文本编码器的隐藏状态。

#### get_guidance_scale_embedding[[diffusers.StableDiffusionXLImg2ImgPipeline.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/v0.43.0/src/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py#L906)

**参数：**

w (`torch.Tensor`) : 生成具有指定 guidance scale 的嵌入向量，以用于后续丰富时间步嵌入。

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

## StableDiffusionXLInpaintPipeline[[diffusers.StableDiffusionXLInpaintPipeline]]

#### diffusers.StableDiffusionXLInpaintPipeline[[diffusers.StableDiffusionXLInpaintPipeline]]

```python
diffusers.StableDiffusionXLInpaintPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, text_encoder_2: CLIPTextModelWithProjection, tokenizer: CLIPTokenizer, tokenizer_2: CLIPTokenizer, unet: UNet2DConditionModel, scheduler: KarrasDiffusionSchedulers, image_encoder: CLIPVisionModelWithProjection = None, feature_extractor: CLIPImageProcessorPil = None, requires_aesthetics_score: bool = False, force_zeros_for_empty_prompt: bool = True, add_watermarker: bool | None = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py#L215)

**参数：**

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

text_encoder (`CLIPTextModel`)：冻结的文本编码器。Stable Diffusion XL 使用 [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel) 的文本部分，具体为 [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) 变体。

text_encoder_2 (` CLIPTextModelWithProjection`)：第二个冻结的文本编码器。Stable Diffusion XL 使用 [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection) 的文本和池化部分，具体为 [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k) 变体。

tokenizer (`CLIPTokenizer`)：[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer) 类的分词器。

tokenizer_2 (`CLIPTokenizer`)：第二个 [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer) 类的 Tokenizer。

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

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) 之一。

requires_aesthetics_score (`bool`，*可选*，默认为 `"False"`)：指示在推理期间是否要求向 `unet` 传递 aesthetic_score 条件。另请参阅 `stabilityai/stable-diffusion-xl-refiner-1-0` 的配置。

force_zeros_for_empty_prompt (`bool`，*可选*，默认为 `"True"`)：是否强制将负提示嵌入始终设置为 0。另请参阅 `stabilityai/stable-diffusion-xl-base-1-0` 的配置。

add_watermarker (`bool`，*可选*)：是否使用 [invisible_watermark 库](https://github.com/ShieldMnt/invisible-watermark/) 为输出图像添加水印。如果未定义，则当该包已安装时默认为 True，否则不使用水印。

使用 Stable Diffusion XL 进行文本到图像生成的 Pipeline。

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

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

#### __调用__[[diffusers.StableDiffusionXLInpaintPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, prompt_2: str | list[str] | None = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, 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 = 0.9999, num_inference_steps: int = 50, timesteps: list[int] = None, sigmas: list[float] = None, denoising_start: float | None = None, denoising_end: float | None = None, guidance_scale: float = 7.5, negative_prompt: str | list[str] | None = None, negative_prompt_2: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, 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, guidance_rescale: float = 0.0, original_size: tuple[int, int] = None, crops_coords_top_left: tuple[int, int] = (0, 0), target_size: tuple[int, int] = None, negative_original_size: tuple[int, int] | None = None, negative_crops_coords_top_left: tuple[int, int] = (0, 0), negative_target_size: tuple[int, int] | None = None, aesthetic_score: float = 6.0, negative_aesthetic_score: float = 2.5, 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[str] = ['latents'], **kwargs)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py#L1080)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的提示词或提示词列表。如果未定义，则必须改为传入 `prompt_embeds`。

prompt_2 (`str` 或 `list[str]`，*可选*)：要发送给 `tokenizer_2` 和 `text_encoder_2` 的提示词或提示词列表。如果未定义，则两个文本编码器均使用 `prompt`。

image (`PIL.Image.Image`) : `Image`，或表示将进行修复的图像批次的张量，*即*图像的部分区域将被 `mask_image` 掩码，并根据 `prompt` 重新绘制。

mask_image (`PIL.Image.Image`) : `Image`，或表示图像批次的张量，用于对 `image` 进行遮罩。遮罩中的白色像素将被重绘，而黑色像素将保留。如果 `mask_image` 是 PIL 图像，在使用前会先转换为单通道（亮度）。如果它是张量，则应包含一个颜色通道（L）而不是三个，因此预期的形状为 `(B, H, W, 1)`。

masked_image_latents (`torch.Tensor`, *可选*) : 掩码图像的预编码潜在表示（用于图像修复）。

height (`int`，*可选*，默认为 self.unet.config.sample_size * self.vae_scale_factor)：生成图像的高度（以像素为单位）。默认设置为 1024 以获得最佳效果。对于 [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0) 以及未在低分辨率上专门微调的检查点，低于 512 像素的效果不佳。

width (`int`，*可选*，默认为 self.unet.config.sample_size * self.vae_scale_factor)：生成图像的像素宽度。默认设置为 1024 以获得最佳效果。对于 [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0) 以及未在低分辨率上专门微调的检查点，低于 512 像素的宽度效果不佳。

padding_mask_crop (`int`, *可选*，默认为 `None`) : 应用于图像和掩码的裁剪边距大小。如果为 `None`，则不对 image 和 mask_image 进行裁剪。如果 `padding_mask_crop` 不为 `None`，则会先找到一个与图像具有相同宽高比且包含所有掩码区域的矩形区域，然后根据 `padding_mask_crop` 扩展该区域。随后，在将图像和 mask_image 调整回原始图像尺寸以进行修复之前，会基于扩展后的区域对它们进行裁剪。当掩码区域较小而图像较大，且包含与修复无关的信息（例如背景）时，此功能非常有用。

strength (`float`, *可选*，默认为 0.9999)：从概念上讲，表示对参考`image`中被掩码部分进行多大程度的变换。取值必须在 0 到 1 之间。`image`将作为起点，`strength`越大，添加的噪声越多。去噪步数取决于初始添加的噪声量。当`strength`为 1 时，添加的噪声达到最大值，去噪过程将运行`num_inference_steps`中指定的完整迭代次数。因此，值为 1 时，基本上会忽略参考`image`中被掩码的部分。请注意，如果`denoising_start`被声明为整数，则`strength`的值将被忽略。

num_inference_steps (`int`, *可选*，默认为 50)：去噪步数。更多的去噪步数通常能带来更高质量的图像，但代价是推理速度变慢。

timesteps (`list[int]`，*可选*)：用于在支持 `set_timesteps` 方法中 `timesteps` 参数的调度器中，指定去噪过程所使用的自定义时间步。如果未定义，则使用传入 `num_inference_steps` 时的默认行为。必须按降序排列。

sigmas (`list[float]`, *可选*) : 用于支持在 `set_timesteps` 方法中接受 `sigmas` 参数的调度器的去噪过程的自定义 sigmas。如果未定义，将使用传入 `num_inference_steps` 时的默认行为。

denoising_start (`float`, *可选*) : 指定时，表示在去噪过程启动前需要跳过的总去噪过程的比例（介于 0.0 和 1.0 之间）。因此，去噪过程的初始部分将被跳过，并假定传入的 `image` 是一张部分去噪的图像。请注意，当指定此参数时，strength 将被忽略。`denoising_start` 参数在将此管道集成到“去噪器混合”多管道配置中时特别有用，详见 [**优化图像输出**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)。

denoising_end (`float`, *可选*) : 指定时，确定在有意提前终止之前，总去噪过程需要完成的比例（介于 0.0 和 1.0 之间）。因此，返回的样本仍将保留大量噪声（大约还需要最后 20% 的时间步），并且应该由一个将 `denoising_start` 设置为 0.8 的后续流水线进行去噪，使其仅对调度器的最后 20% 进行去噪。理想情况下，当此流水线作为“去噪器混合”多流水线设置的一部分时，应使用 denoising_end 参数，如 [**优化图像输出**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output) 中所述。

guidance_scale (`float`，*可选*，默认值为 7.5)：如[Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598)中定义的引导尺度。`guidance_scale` 定义为[Imagen Paper](https://huggingface.co/papers/2205.11487)中公式 2 的 `w`。通过设置 `guidance_scale > 1` 来启用引导尺度。较高的引导尺度会促使生成与文本 `prompt` 紧密关联的图像，但通常以牺牲图像质量为代价。

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的负面提示词。如果未定义，则必须传入 `negative_prompt_embeds`。当不使用引导时（即 `guidance_scale` 小于 `1` 时），此参数将被忽略。

negative_prompt_2 (`str` 或 `list[str]`，*可选*)：要发送给 `tokenizer_2` 和 `text_encoder_2` 的提示词或提示词列表，用于引导图像生成。如果未定义，则两个文本编码器都会使用 `negative_prompt`。

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，文本嵌入将从 `prompt` 输入参数生成。

negative_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的负向文本嵌入。可用于轻松调整文本输入，*例如* 提示词权重。如果未提供，negative_prompt_embeds 将从 `negative_prompt` 输入参数生成。

pooled_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的池化文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，将从 `prompt` 输入参数生成池化文本嵌入。

negative_pooled_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的负向池化文本嵌入。可用于轻松调整文本输入，*例如* 提示词权重。如果未提供，将从 `negative_prompt` 输入参数生成 pooled negative_prompt_embeds。

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` 输入参数计算得出。

num_images_per_prompt (`int`，*可选*，默认为 1)：每个提示词生成的图像数量。

eta (`float`，*可选*，默认值为 0.0)：对应 DDIM 论文中的参数 eta (η)：https://huggingface.co/papers/2010.02502。仅适用于 [schedulers.DDIMScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/ddim#diffusers.DDIMScheduler)，对其他调度器将被忽略。

generator (`torch.Generator`, *可选*) : 一个或一组 [torch 生成器](https://pytorch.org/docs/stable/generated/torch.Generator.html)，用于使生成过程具有确定性。

latents (`torch.Tensor`, *可选*) : 预先生成的噪声潜变量，从高斯分布中采样得到，用作图像生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供，将通过使用提供的随机`generator`进行采样来生成潜变量张量。

output_type (`str`，*可选*，默认为 `"pil"`)：生成图像的输出格式。可选 [PIL](https://pillow.readthedocs.io/en/stable/)：`PIL.Image.Image` 或 `np.array`。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) 而不是普通元组。

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

original_size (`tuple[int]`，*可选*，默认为 (1024, 1024))：如果 `original_size` 与 `target_size` 不同，图像将看起来像是被下采样或上采样了。如果未指定，`original_size` 默认为 `(height, width)`。这是 SDXL 微条件的一部分，如 [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952) 第 2.2 节所述。

crops_coords_top_left (`tuple[int]`，*可选*，默认值为 (0, 0))：`crops_coords_top_left` 可用于生成一张看似从 `crops_coords_top_left` 位置向下裁剪的图像。通常将 `crops_coords_top_left` 设置为 (0, 0) 即可获得构图良好、居中效果佳的图像。这是 SDXL 微条件的一部分，详见 [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952) 中的第 2.2 节。

target_size (`tuple[int]`，*可选*，默认值为 (1024, 1024))：在大多数情况下，应将 `target_size` 设置为生成图像所需的宽度和高度。如果未指定，则默认为 `(height, width)`。这是 [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952) 第 2.2 节中所述 SDXL 微条件化的一部分。

negative_original_size (`tuple[int]`，*可选*，默认为 (1024, 1024))：用于基于特定的图像分辨率对生成过程进行负向条件控制。这是 SDXL 微条件化的一部分，如 [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952) 第 2.2 节所述。更多信息请参阅此 issue 讨论：https://github.com/huggingface/diffusers/issues/4208。

negative_crops_coords_top_left (`tuple[int]`，*可选*，默认值为 (0, 0))：用于根据特定的裁剪坐标对生成过程施加负向条件。这是 SDXL 微条件的一部分，详见 [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952) 中的第 2.2 节。更多信息请参阅此 issue 讨论：https://github.com/huggingface/diffusers/issues/4208。

negative_target_size (`tuple[int]`，*可选*，默认值为 (1024, 1024))：用于根据目标图像分辨率对生成过程施加负向条件。在大多数情况下，它应与 `target_size` 相同。这是 SDXL 微条件的一部分，如 [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952) 第 2.2 节所述。更多信息，请参阅此 issue 讨论：https://github.com/huggingface/diffusers/issues/4208。

aesthetic_score (`float`，*可选*，默认值为 6.0)：用于通过影响正向文本条件来模拟生成图像的美学评分。这是 SDXL 微条件化的一部分，详见 [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952) 中的第 2.2 节。

negative_aesthetic_score (`float`，*可选*，默认值为 2.5)：[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952) 第 2.2 节中所述的 SDXL 微条件（micro-conditioning）的一部分。可通过影响负向文本条件来模拟生成图像的美学评分。

guidance_rescale (`float`, *可选*，默认为 0.0) : [常见的扩散噪声调度和采样步骤存在缺陷](https://arxiv.org/pdf/2305.08891.pdf) 中的 guidance rescale 因子。

clip_skip (`int`, *可选*) : 在计算提示嵌入时，从 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` 属性中列出的变量。

**返回：** `~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput` 或 `tuple`

如果 `return_dict` 为 True，则返回 `~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`，否则返回 `tuple. `tuple。当返回元组时，第一个元素是一个包含生成图像的列表。

调用生成 pipeline 时调用的函数。

示例：
```py
>>> import torch
>>> from diffusers import StableDiffusionXLInpaintPipeline
>>> from diffusers.utils import load_image

>>> pipe = StableDiffusionXLInpaintPipeline.from_pretrained(
...     "stabilityai/stable-diffusion-xl-base-1.0",
...     torch_dtype=torch.float16,
...     variant="fp16",
...     use_safetensors=True,
... )
>>> pipe.to("cuda")

>>> 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 = load_image(img_url).convert("RGB")
>>> mask_image = load_image(mask_url).convert("RGB")

>>> prompt = "A majestic tiger sitting on a bench"
>>> image = pipe(
...     prompt=prompt, image=init_image, mask_image=mask_image, num_inference_steps=50, strength=0.80
... ).images[0]
```

#### encode_prompt[[diffusers.StableDiffusionXLInpaintPipeline.encode_prompt]]

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

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py#L405)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：要编码的提示

prompt_2 (`str` 或 `list[str]`，*可选*)：要发送给 `tokenizer_2` 和 `text_encoder_2` 的提示词或提示词列表。如果未定义，则两个文本编码器均使用 `prompt`。

device : (`torch.device`): torch 设备

num_images_per_prompt (`int`) : 每个提示词应生成的图像数量

do_classifier_free_guidance (`bool`) : 是否使用 classifier free guidance

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的负面提示词。如果未定义，则必须传入 `negative_prompt_embeds`。当不使用引导时（即 `guidance_scale` 小于 `1` 时），此参数将被忽略。

negative_prompt_2 (`str` 或 `list[str]`，*可选*)：要发送给 `tokenizer_2` 和 `text_encoder_2` 的提示词或提示词列表，用于引导图像生成。如果未定义，则两个文本编码器都会使用 `negative_prompt`。

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，文本嵌入将从 `prompt` 输入参数生成。

negative_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的负向文本嵌入。可用于轻松调整文本输入，*例如* 提示词权重。如果未提供，negative_prompt_embeds 将从 `negative_prompt` 输入参数生成。

pooled_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的池化文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，将从 `prompt` 输入参数生成池化文本嵌入。

negative_pooled_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的负向池化文本嵌入。可用于轻松调整文本输入，*例如* 提示词权重。如果未提供，将从 `negative_prompt` 输入参数生成 pooled negative_prompt_embeds。

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

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

将提示词编码为文本编码器的隐藏状态。

#### get_guidance_scale_embedding[[diffusers.StableDiffusionXLInpaintPipeline.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/v0.43.0/src/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py#L1011)

**参数：**

w (`torch.Tensor`) : 生成具有指定 guidance scale 的嵌入向量，以用于后续丰富时间步嵌入。

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

