# Pipelines

Pipelines 提供了一种简单的方式来运行最先进的扩散模型进行推理，它将所有必要的组件（多个独立训练的模型、调度器和处理器）封装到一个端到端的类中。Pipelines 具有灵活性，可以适配使用不同的调度器，甚至不同的模型组件。

所有流水线都基于 [DiffusionPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/overview#diffusers.DiffusionPipeline) 基类构建，该基类提供了加载、下载和保存所有组件的基本功能。使用 [from_pretrained()](/docs/diffusers/v0.43.0/zh/api/pipelines/overview#diffusers.DiffusionPipeline.from_pretrained) 加载的特定流水线类型（例如 [StableDiffusionPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/stable_diffusion/text2img#diffusers.StableDiffusionPipeline)）会被自动检测，其流水线组件会被加载并传递给流水线的 `__init__` 函数。

> [!WARNING]
> 不建议使用 [DiffusionPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/overview#diffusers.DiffusionPipeline) 类进行训练。扩散管线的各个组件（例如 [UNet2DModel](/docs/diffusers/v0.43.0/zh/api/models/unet2d#diffusers.UNet2DModel) 和 [UNet2DConditionModel](/docs/diffusers/v0.43.0/zh/api/models/unet2d-cond#diffusers.UNet2DConditionModel)）通常是单独训练的，因此我们建议直接对这些组件进行操作。
>
> 
>
> Pipelines 不提供任何训练功能。您会注意到，由于 [`torch.no_grad`](https://pytorch.org/docs/stable/generated/torch.no_grad.html) 装饰器应用于 `__call__()` 方法，PyTorch 的 autograd 已被禁用，因为 pipelines 不应用于训练。如果您对训练感兴趣，请查看 [Training](../../training/overview) 指南！

使用侧边栏中的 **API > Pipelines** 可按模态浏览所有 pipeline 参考文档。对于面向任务的工作流，请从 [Quickstart](../../quicktour) 或诸如 [text-to-image](../../using-diffusers/conditional_image_generation)、[image-to-image](../../using-diffusers/img2img)、[inpainting](../../using-diffusers/inpaint) 或 [video generation](../../using-diffusers/text-img2vid) 等指南开始。

## DiffusionPipeline[[diffusers.DiffusionPipeline]]

#### diffusers.DiffusionPipeline[[diffusers.DiffusionPipeline]]

```python
diffusers.DiffusionPipeline()
```

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

所有管道的基类。

[DiffusionPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/overview#diffusers.DiffusionPipeline) 存储扩散流水线的所有组件（模型、调度器和处理器），并提供用于加载、下载和保存模型的方法。它还包含以下方法：

- 将所有 PyTorch 模块移动到您选择的设备上
- 启用/禁用去噪迭代的进度条

类属性：

- **config_name** (`str`) -- 用于存储扩散流水线所有组件的类名和模块名的配置文件名。
- **_optional_components** (`List[str]`) -- 所有无需传入 pipeline 即可正常工作的可选组件列表（应由子类重写）。

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

```python
__call__(*args, **kwargs)
```

将 self 作为函数调用。

#### device[[diffusers.DiffusionPipeline.device]]

```python
device()
```

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

**返回：** `torch.device`

流水线所在的 torch 设备。当组件被拆分到不同设备上时（例如，文本编码器在 CPU 上，而去噪主干网络在加速器上运行），将返回加速器设备。

#### 到[[diffusers.DiffusionPipeline.to]]

```python
to(*args, **kwargs)
```

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

**参数：**

dtype (`torch.dtype`，*可选*)：返回一个使用指定 [`dtype`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.dtype) 的 pipeline

device (`torch.Device`, *可选*) : 返回一个使用指定 [`device`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.device) 的 pipeline

silence_dtype_warnings (`str`，*可选*，默认为 `False`)：如果目标 `dtype` 与目标 `device` 不兼容，是否省略警告。

**返回：** [DiffusionPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/overview#diffusers.DiffusionPipeline)

Pipeline 已转换为指定的 `dtype` 和/或 `dtype`。

执行 Pipeline 的 dtype 和/或 device 转换。torch.dtype 和 torch.device 是从 `self.to(*args, **kwargs).` 的参数中推断出来的。

> [!TIP] > 如果 pipeline 已经具有正确的 torch.dtype 和 torch.device，则会直接返回。
否则，返回的 pipeline 是 self 的副本，具有所需的 torch.dtype 和 torch.device。

以下是调用 `to` 的方式：

- `to(dtype, silence_dtype_warnings=False) → DiffusionPipeline` 返回一个具有指定 [`dtype`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.dtype) 的 pipeline
- `to(device, silence_dtype_warnings=False) → DiffusionPipeline` 用于返回一个使用指定 [`device`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.device) 的 pipeline
- `to(device=None, dtype=None, silence_dtype_warnings=False) → DiffusionPipeline` 返回一个具有指定 [`device`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.device) 和 [`dtype`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.dtype) 的 pipeline

#### 组件[[diffusers.DiffusionPipeline.components]]

```python
components()
```

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

`self.components` 属性可用于在不重新分配额外内存的情况下，使用相同的权重和配置运行不同的流水线。

Returns (`dict`)：一个包含初始化流水线所需所有模块的字典。

示例：

```py
>>> from diffusers import (
...     StableDiffusionPipeline,
...     StableDiffusionImg2ImgPipeline,
...     StableDiffusionInpaintPipeline,
... )

>>> text2img = StableDiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5")
>>> img2img = StableDiffusionImg2ImgPipeline(**text2img.components)
>>> inpaint = StableDiffusionInpaintPipeline(**text2img.components)
```

#### disable_attention_slicing[[diffusers.DiffusionPipeline.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`，则注意力将一次性计算完成。

#### disable_xformers_memory_efficient_attention[[diffusers.DiffusionPipeline.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/) 的内存高效注意力。

#### 下载[[diffusers.DiffusionPipeline.download]]

```python
download(pretrained_model_name, **kwargs)
```

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

**参数：**

pretrained_model_name (`str` 或 `os.PathLike`，*可选*)：一个字符串，即托管在 Hub 上的预训练流水线的 *repository id*（例如 `CompVis/ldm-text2im-large-256`）。

custom_pipeline (`str`, *可选*) : 可以是以下之一：  - 一个字符串，即托管在 Hub 上的预训练流水线的 *repository id*（例如 `CompVis/ldm-text2im-large-256`）。该仓库必须包含一个名为 `pipeline.py` 的文件，用于定义自定义流水线。  - 一个字符串，即托管在 GitHub [Community](https://github.com/huggingface/diffusers/tree/main/examples/community) 下的社区流水线的 *文件名*。有效的文件名必须与文件名匹配，而不是流水线脚本（使用 `clip_guided_stable_diffusion` 而不是 `clip_guided_stable_diffusion.py`）。社区流水线始终从 GitHub 的当前 `main` 分支加载。  - 指向包含自定义流水线的 *目录* 的路径（`./my_pipeline_directory/`）。该目录必须包含一个名为 `pipeline.py` 的文件，用于定义自定义流水线。  > [!WARNING] > 🧪 这是一个实验性功能，未来可能会发生变化。  有关如何加载和创建自定义流水线的更多信息，请参阅 [如何贡献社区流水线](https://huggingface.co/docs/diffusers/main/en/using-diffusers/contribute_pipeline)。

force_download (`bool`，*可选*，默认为 `False`)：是否强制（重新）下载模型权重和配置文件，如果存在缓存版本则覆盖它们。

proxies (`Dict[str, str]`，*可选*)：一个字典，按协议或端点指定要使用的代理服务器，例如 `{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}`。每次请求都会使用这些代理。

output_loading_info(`bool`，*可选*，默认为 `False`)：是否同时返回一个包含缺失键、意外键和错误消息的字典。

local_files_only (`bool`，*可选*，默认为 `False`)：是否仅加载本地模型权重和配置文件。如果设置为 `True`，则不会从 Hub 下载模型。

token (`str` 或 *bool*，*可选*) : 用于远程文件的 HTTP 承载者授权令牌。如果为 `True`，则使用由 `diffusers-cli login` 生成的令牌（存储在 `~/.huggingface` 中）。

revision (`str`，*可选*，默认为 `"main"`)：要使用的特定模型版本。它可以是分支名称、标签名称、提交 ID，或 Git 允许的任何标识符。

custom_revision (`str`，*可选*，默认为 `"main"`)：要使用的特定模型版本。它可以是分支名称、标签名称或提交 ID，类似于从 Hub 加载自定义流水线时的 `revision`。当从 GitHub 加载自定义流水线时，它可以是 🤗 Diffusers 的版本号；否则，从 Hub 加载时默认为 `"main"`。

mirror (`str`, *可选*) : 用于解决在中国下载模型时可能遇到的访问问题的镜像源。我们不保证该源的时效性或安全性，详情请参阅镜像站点。

variant (`str`, *可选*) : 从指定的变体文件名（例如 `"fp16"` 或 `"ema"`）加载权重。

use_safetensors (`bool`，*可选*，默认为 `None`)：如果设置为 `None`，则在 safetensors 权重可用**且**已安装 safetensors 库的情况下，会下载 safetensors 权重。如果设置为 `True`，则强制从 safetensors 权重加载模型。如果设置为 `False`，则不加载 safetensors 权重。

use_onnx (`bool`，*可选*，默认为 `False`)：如果设置为 `True`，则只要存在 ONNX 权重，就始终会下载它们。如果设置为 `False`，则永远不会下载 ONNX 权重。默认情况下，`use_onnx` 的默认值为 `_is_onnx` 类属性，对于非 ONNX 流水线，该属性为 `False`；对于 ONNX 流水线，该属性为 `True`。ONNX 权重包括以 `.onnx` 和 `.pb` 结尾的两种文件。

trust_remote_code (`bool`，*可选*，默认为 `False`)：是否允许使用在 Hub 上以独立文件定义的自定义 pipeline 和组件。此选项仅应为您信任且已阅读过其代码的仓库设置为 `True`，因为它会在您的本地机器上执行 Hub 上存在的代码。

use_flashpack (`bool`，*可选*，默认为 `False`)：如果设置为 `True`，则只要存在 FlashPack 权重，就始终会下载它们。如果设置为 `False`，则永远不会下载 FlashPack 权重。

**返回：** `os.PathLike`

已下载流水线的路径。

从预训练流水线权重中下载并缓存一个 PyTorch 扩散流水线。

> [!TIP] > 若要使用私有或 [受限模型](https://huggingface.co/docs/hub/models-gated#gated-models)，请先登录
使用 hf > auth login

#### enable_attention_slicing[[diffusers.DiffusionPipeline.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]
```

#### enable_group_offload[[diffusers.DiffusionPipeline.enable_group_offload]]

```python
enable_group_offload(onload_device: device, offload_device: device = torch.device(), offload_type: str = 'block_level', num_blocks_per_group: int | None = None, non_blocking: bool = False, use_stream: bool = False, record_stream: bool = False, low_cpu_mem_usage = False, offload_to_disk_path: str | None = None, exclude_modules: str | list[str] | None = None)
```

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

**参数：**

onload_device (`torch.device`)：该组模块所加载到的设备。

offload_device (`torch.device`，默认为 `torch.device("cpu")`)：模块组被卸载到的设备。通常应为 CPU。默认值为 CPU。

offload_type (`str` 或 `GroupOffloadingType`，默认为 "block_level") : 要应用的卸载类型。可以是 "block_level" 或 "leaf_level" 之一。默认为 "block_level"。

offload_to_disk_path (`str`，*可选*，默认为 `None`)：参数将被卸载到的目录路径。在内存受限的环境中，若希望获得合理的速度与内存之间的权衡，设置此选项会很有用。

num_blocks_per_group (`int`, *可选*) : 当使用 offload_type="block_level" 时，每个组中的块数。使用 offload_type="block_level" 时，此参数为必填项。

non_blocking (`bool`，默认为 `False`)：如果为 True，则使用非阻塞数据传输来执行卸载和加载。

use_stream (`bool`，默认为 `False`)：如果为 True，则使用 CUDA 流异步执行卸载和加载操作。这有助于重叠计算和数据传输。

record_stream (`bool`，默认为 `False`)：当与 `use_stream` 一起启用时，它会将当前张量标记为已被此流使用。这种方式速度更快，但会略微增加内存占用。有关更多详细信息，请参阅 [PyTorch 官方文档](https://pytorch.org/docs/stable/generated/torch.Tensor.record_stream.html)。

low_cpu_mem_usage (`bool`，默认为 `False`)：如果为 True，则通过即时固定张量（而非预先固定）来最小化 CPU 内存使用。此选项仅在使用流式 CPU 卸载（即 `use_stream=True`）时才有意义。当 CPU 内存成为瓶颈时，此选项可能有用，但可能会抵消使用流所带来的好处。

exclude_modules (`Union[str, List[str]]`，默认为 `None`)：要从 offloading 中排除的模块列表。

将组卸载（group offloading）应用于 torch.nn.Module 的内部层。要了解什么是组卸载以及它在哪些场景下具有优势，我们首先需要介绍其他受支持的卸载方法的工作原理。

通常，卸载操作在两个层面进行：
- 模块级：在 Diffusers 中，可以使用 `ModelMixin::enable_model_cpu_offload()` 方法启用此功能。它
其工作原理是将流水线的每个组件卸载到 CPU 上进行存储，并在需要计算时将其加载到加速器设备上。与将所有组件都保留在加速器上相比，这种方法在内存效率上更高，但内存需求仍然相当高。要使该方法正常工作，所需的内存量相当于运行时数据类型下模型的大小加上最大的中间激活张量的大小，以便能够完成前向传播。
- 叶子级别：在 Diffusers 中，可以使用 `ModelMixin::enable_sequential_cpu_offload()` 方法启用此功能。它
其工作原理是将计算图中最底层的叶子级参数卸载到 CPU 上进行存储，并在计算时仅将这些叶子参数加载到加速器设备上。这种方式使用的加速器内存最少，但由于设备同步次数过多，速度可能会变慢。

Group offloading 是上述两种方法之间的折中方案。它通过卸载内部层的分组（即 `torch.nn.ModuleList` 或 `torch.nn.Sequential`）来实现。与模块级卸载相比，该方法占用的内存更少。同时，由于减少了设备同步的次数，其速度也快于叶子级/顺序卸载。

另一项受支持的功能（适用于支持异步数据传输流的 CUDA 设备）是能够重叠数据传输与计算，从而与顺序卸载相比缩短整体执行时间。该功能通过带流的层预取实现，即在执行当前层的同时，下一层开始向加速器设备加载——这会使内存需求略有增加。请注意，此实现同样支持叶级卸载，但在使用流时速度可以大幅提升。

示例：
```python
>>> from diffusers import DiffusionPipeline
>>> import torch

>>> pipe = DiffusionPipeline.from_pretrained("Qwen/Qwen-Image", dtype=torch.bfloat16)

>>> pipe.enable_group_offload(
...     onload_device=torch.device("cuda"),
...     offload_device=torch.device("cpu"),
...     offload_type="leaf_level",
...     use_stream=True,
... )
>>> image = pipe("a beautiful sunset").images[0]
```

#### enable_model_cpu_offload[[diffusers.DiffusionPipeline.enable_model_cpu_offload]]

```python
enable_model_cpu_offload(gpu_id: int | None = None, device: typing.Union[torch.device, str] = None)
```

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

**参数：**

gpu_id (`int`, *可选*) : 推理中要使用的加速器 ID。如果未指定，则默认为 0。

device (`torch.Device` 或 `str`，*可选*，默认为 None) : 推理中要使用的加速器的 PyTorch 设备类型。如果未指定，将自动检测可用的加速器并使用。

使用 accelerate 将所有模型卸载到 CPU，在性能影响较小的情况下降低内存占用。与 `enable_sequential_cpu_offload` 相比，该方法在调用某个模型的 `forward` 方法时，将整个模型一次性移至加速器，并且该模型会一直保留在加速器上，直到下一个模型开始运行。与 `enable_sequential_cpu_offload` 相比，此方法的内存节省幅度较小，但由于 `unet` 的迭代执行，其性能要出色得多。

#### enable_sequential_cpu_offload[[diffusers.DiffusionPipeline.enable_sequential_cpu_offload]]

```python
enable_sequential_cpu_offload(gpu_id: int | None = None, device: typing.Union[torch.device, str] = None)
```

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

**参数：**

gpu_id (`int`, *可选*) : 推理中要使用的加速器 ID。如果未指定，则默认为 0。

device (`torch.Device` 或 `str`，*可选*，默认为 None) : 推理中要使用的加速器的 PyTorch 设备类型。如果未指定，将自动检测可用的加速器并使用。

使用 🤗 Accelerate 将所有模型卸载到 CPU，从而显著降低内存占用。调用时，所有 `torch.nn.Module` 组件（`self._exclude_from_cpu_offload` 中的除外）的状态字典会被保存到 CPU，然后移至 `torch.device('meta')`，仅在其特定子模块的 `forward` 方法被调用时才加载到加速器上。卸载以子模块为单位进行。与 `enable_model_cpu_offload` 相比，内存节省更多，但性能较低。

#### enable_xformers_memory_efficient_attention[[diffusers.DiffusionPipeline.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)
```

#### from_pipe[[diffusers.DiffusionPipeline.from_pipe]]

```python
from_pipe(pipeline, **kwargs)
```

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

**参数：**

pipeline (`DiffusionPipeline`)：用于创建新 pipeline 的源 pipeline。

**返回：** `DiffusionPipeline`

一个具有与 `pipeline` 相同权重和配置的新流水线。

从给定的流水线创建一个新的流水线。此方法适用于利用现有流水线的组件创建新流水线，而无需重新分配额外的内存。

示例：

```py
>>> from diffusers import StableDiffusionPipeline, StableDiffusionSAGPipeline

>>> pipe = StableDiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5")
>>> new_pipe = StableDiffusionSAGPipeline.from_pipe(pipe)
```

#### from_pretrained[[diffusers.DiffusionPipeline.from_pretrained]]

```python
from_pretrained(pretrained_model_name_or_path: str | os.PathLike, **kwargs)
```

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

**参数：**

pretrained_model_name_or_path (`str` 或 `os.PathLike`，*可选*) : 可以是以下之一： - 一个字符串，即托管在 Hub 上的预训练流水线的 *repo id*（例如 `CompVis/ldm-text2im-large-256`）。 - 一个指向 *目录* 的路径（例如 `./my_pipeline_directory/`），其中包含使用 [save_pretrained()](/docs/diffusers/v0.43.0/zh/api/pipelines/overview#diffusers.DiffusionPipeline.save_pretrained) 保存的流水线权重。

dtype (`torch.dtype` 或 `dict[str, Union[str, torch.dtype]]`，*可选*)：覆盖默认的 `torch.dtype`，并使用另一种 dtype 加载模型。若要为不同的子模型指定不同的 dtype，请传入一个 `dict`（例如 `{'transformer': torch.bfloat16, 'vae': torch.float16}`）。使用 `default` 为未指定的组件设置默认 dtype（例如 `{'transformer': torch.bfloat16, 'default': torch.float16}`）。如果某个组件未指定且未设置默认值，则使用 `torch.float32`。

custom_pipeline (`str`, *可选*) : > [!WARNING] > 🧪 这是一个实验性功能，未来可能会发生变化。 可以是以下之一： - 一个字符串，即托管在 Hub 上的自定义流水线的 *repo id*（例如 `hf-internal-testing/diffusers-dummy-pipeline`）。该仓库必须包含一个名为 pipeline.py 的文件，用于定义自定义流水线。 - 一个字符串，即托管在 GitHub [Community](https://github.com/huggingface/diffusers/tree/main/examples/community) 下的社区流水线的 *文件名*。有效的文件名必须与文件名匹配，而不是流水线脚本（使用 `clip_guided_stable_diffusion` 而不是 `clip_guided_stable_diffusion.py`）。社区流水线始终从 GitHub 的当前 main 分支加载。 - 指向包含自定义流水线的目录的路径（`./my_pipeline_directory/`）。该目录必须包含一个名为 `pipeline.py` 的文件，用于定义自定义流水线。 有关如何加载和创建自定义流水线的更多信息，请参阅 [加载和添加自定义流水线](https://huggingface.co/docs/diffusers/using-diffusers/custom_pipeline_overview)

force_download (`bool`，*可选*，默认为 `False`)：是否强制（重新）下载模型权重和配置文件，如果存在缓存版本则覆盖它们。

cache_dir (`Union[str, os.PathLike]`，*可选*)：如果未使用标准缓存，则已下载的预训练模型配置将缓存到的目录路径。

proxies (`Dict[str, str]`，*可选*)：一个字典，按协议或端点指定要使用的代理服务器，例如 `{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}`。每次请求都会使用这些代理。

output_loading_info(`bool`，*可选*，默认为 `False`)：是否同时返回一个包含缺失键、意外键和错误消息的字典。

local_files_only (`bool`，*可选*，默认为 `False`)：是否仅加载本地模型权重和配置文件。如果设置为 `True`，则不会从 Hub 下载模型。

token (`str` 或 *bool*，*可选*) : 用于远程文件的 HTTP 承载者授权令牌。如果为 `True`，则使用由 `diffusers-cli login` 生成的令牌（存储在 `~/.huggingface` 中）。

revision (`str`，*可选*，默认为 `"main"`)：要使用的特定模型版本。它可以是分支名称、标签名称、提交 ID，或 Git 允许的任何标识符。

custom_revision (`str`, *可选*) : 要使用的特定模型版本。它可以是分支名称、标签名称或提交 ID，类似于从 Hub 加载自定义流水线时的 `revision`。默认使用最新的稳定版 🤗 Diffusers 版本。

mirror (`str`, *可选*) : 用于解决在中国下载模型时可能遇到的访问问题的镜像源。我们不保证该源的时效性或安全性，详情请参阅镜像站点。

device_map (`str`, *可选*) : 指定流水线中不同组件应如何放置在可用设备上的策略。目前仅支持 "balanced" `device_map`。有关更多信息，请参阅 [此处](https://huggingface.co/docs/diffusers/main/en/tutorials/inference_with_big_models#device-placement)。

max_memory (`Dict`, *可选*) : 用于指定最大内存的设备标识符字典。如果未设置，则默认为每个 GPU 的最大可用内存和可用的 CPU 内存。

offload_folder (`str` 或 `os.PathLike`，*可选*)：如果 device_map 包含值 `"disk"`，则指定用于卸载权重的路径。

offload_state_dict (`bool`, *可选*) : 如果为 `True`，则临时将 CPU 状态字典卸载到硬盘，以避免在 CPU 状态字典的权重加上检查点中最大的分片无法容纳时耗尽 CPU 内存。当存在磁盘卸载时，默认值为 `True`。

low_cpu_mem_usage (`bool`，*可选*，如果 torch 版本 >= 1.9.0 则默认为 `True`，否则为 `False`)：通过仅加载预训练权重而不初始化权重来加速模型加载。加载模型时，此参数还尝试将 CPU 内存使用量（包括峰值内存）控制在不超过 1 倍模型大小。仅支持 PyTorch >= 1.9.0。如果您使用的是旧版本的 PyTorch，将此参数设置为 `True` 将引发错误。

use_safetensors (`bool`，*可选*，默认为 `None`)：如果设置为 `None`，则在 safetensors 权重可用**且**已安装 safetensors 库的情况下，会下载 safetensors 权重。如果设置为 `True`，则强制从 safetensors 权重加载模型。如果设置为 `False`，则不加载 safetensors 权重。

use_onnx (`bool`，*可选*，默认为 `None`)：如果设置为 `True`，只要存在 ONNX 权重，就始终会下载它们。如果设置为 `False`，则永远不会下载 ONNX 权重。默认情况下，`use_onnx` 的默认值为 `_is_onnx` 类属性，对于非 ONNX 流水线，该属性为 `False`；对于 ONNX 流水线，该属性为 `True`。ONNX 权重包括以 `.onnx` 和 `.pb` 结尾的两种文件。

kwargs （其余关键字参数字典，*可选*）：可用于覆盖加载和可保存的变量（特定 pipeline 类的 pipeline 组件）。被覆盖的组件会直接传递给 pipeline 的 `__init__` 方法。更多信息请参见下方示例。

variant (`str`, *可选*) : 从指定的变体文件名（例如 `"fp16"` 或 `"ema"`）加载权重。

disable_mmap ('bool', *可选*，默认为 'False')：是否在加载 Safetensors 模型时禁用 mmap。当模型位于网络挂载点或硬盘上时，此选项可能表现更佳，因为这些存储设备可能无法很好地处理 mmap 的频繁寻址操作。

从预训练流水线权重实例化一个 PyTorch 扩散流水线。

默认情况下，pipeline 会设置为评估模式（`model.eval()`）。

如果出现以下错误消息，您需要针对下游任务微调权重：

```
Some weights of UNet2DConditionModel were not initialized from the model checkpoint at stable-diffusion-v1-5/stable-diffusion-v1-5 and are newly initialized because the shapes did not match:
- conv_in.weight: found shape torch.Size([320, 4, 3, 3]) in the checkpoint and torch.Size([320, 9, 3, 3]) in the model instantiated
You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
```

> [!TIP] > 若要使用私有或 [受限](https://huggingface.co/docs/hub/models-gated#gated-models) 模型，请先登录
使用 `hf > auth login`。

示例：

```py
>>> from diffusers import DiffusionPipeline

>>> # Download pipeline from huggingface.co and cache.
>>> pipeline = DiffusionPipeline.from_pretrained("CompVis/ldm-text2im-large-256")

>>> # Download pipeline that requires an authorization token
>>> # For more information on access tokens, please refer to this section
>>> # of the documentation](https://huggingface.co/docs/hub/security-tokens)
>>> pipeline = DiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5")

>>> # Use a different scheduler
>>> from diffusers import LMSDiscreteScheduler

>>> scheduler = LMSDiscreteScheduler.from_config(pipeline.scheduler.config)
>>> pipeline.scheduler = scheduler
```

#### maybe_free_model_hooks[[diffusers.DiffusionPipeline.maybe_free_model_hooks]]

```python
maybe_free_model_hooks()
```

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

执行以下操作的方法：
- 卸载所有组件。
- 移除使用 `enable_model_cpu_offload` 时添加的所有模型钩子，然后重新应用它们。如果模型未被卸载，此函数将不执行任何操作。
- 如果去噪器组件的状态ful diffusers 钩子是通过 `register_hook()` 添加的，则重置这些钩子。

请确保将此函数添加到您的 pipeline 的 `__call__` 函数末尾，以便在应用 `enable_model_cpu_offload` 时能够正确运行。

#### numpy_to_pil[[diffusers.DiffusionPipeline.numpy_to_pil]]

```python
numpy_to_pil(images)
```

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

将 NumPy 图像或一批图像转换为 PIL 图像。

#### remove_all_hooks[[diffusers.DiffusionPipeline.remove_all_hooks]]

```python
remove_all_hooks()
```

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

移除使用 `enable_sequential_cpu_offload` 或 `enable_model_cpu_offload` 时添加的所有钩子。

#### reset_device_map[[diffusers.DiffusionPipeline.reset_device_map]]

```python
reset_device_map()
```

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

将设备映射（如果存在）重置为 None。

#### save_pretrained[[diffusers.DiffusionPipeline.save_pretrained]]

```python
save_pretrained(save_directory: str | os.PathLike, safe_serialization: bool = True, variant: str | None = None, max_shard_size: int | str | None = None, push_to_hub: bool = False, use_flashpack: bool = False, **kwargs)
```

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

**参数：**

save_directory (`str` 或 `os.PathLike`)：用于保存 pipeline 的目录。如果该目录不存在，将会自动创建。

safe_serialization (`bool`，*可选*，默认为 `True`)：是否使用 `safetensors` 保存模型，还是使用传统的 PyTorch 方式（通过 `pickle`）。

variant (`str`, *可选*) : 如果指定，权重将以 `pytorch_model.<variant>.bin` 格式保存。

max_shard_size (`int` 或 `str`，默认为 `None`)：分片之前检查点的最大大小。分片后的检查点每个的大小都将小于此值。如果以字符串形式表示，需要是数字后跟一个单位（例如 `"5GB"`）。如果以整数形式表示，单位为字节。请注意，从 2024 年 10 月开始，经过一段时间后，此限制将会降低，以便用户升级到 `diffusers` 的最新版本。这是为了在 Hugging Face 生态系统的不同库（例如 `transformers` 和 `accelerate`）之间为此参数建立统一的默认大小。

push_to_hub (`bool`，*可选*，默认为 `False`)：是否在保存模型后将其推送到 Hugging Face 模型库。您可以通过 `repo_id` 指定要推送到的仓库（默认使用您命名空间中 `save_directory` 的名称）。

kwargs (`Dict[str, Any]`，*可选*)：传递给 [push_to_hub()](/docs/diffusers/v0.43.0/zh/api/schedulers/overview#diffusers.utils.PushToHubMixin.push_to_hub) 方法的额外关键字参数。

将流水线中所有可保存的变量保存到目录中。如果某个流水线变量的类同时实现了保存和加载方法，则该变量可以被保存和加载。使用 [from_pretrained()](/docs/diffusers/v0.43.0/zh/api/pipelines/overview#diffusers.DiffusionPipeline.from_pretrained) 类方法即可轻松重新加载流水线。

#### diffusers.StableDiffusionMixin.enable_freeu[[diffusers.StableDiffusionMixin.enable_freeu]]

```python
diffusers.StableDiffusionMixin.enable_freeu(s1: float, s2: float, b1: float, b2: float)
```

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

**参数：**

s1 (`float`) : 用于第一阶段以衰减跳跃特征贡献的缩放因子。这样做是为了缓解增强去噪过程中的“过度平滑效应”。

s2 (`float`) : 用于阶段 2 的缩放因子，用于衰减跳跃特征的贡献。这样做是为了缓解增强去噪过程中的“过度平滑效应”。

b1 (`float`) : 用于放大骨干网络特征贡献的阶段 1 缩放因子。

b2 (`float`) : 用于放大骨干网络特征贡献的第二阶段缩放因子。

启用 FreeU 机制，如 https://huggingface.co/papers/2309.11497 所述。

缩放因子后面的后缀表示它们被应用的阶段。

有关适用于 Stable Diffusion v1、v2 和 Stable Diffusion XL 等不同流水线的已知效果良好的取值组合，请参阅[官方仓库](https://github.com/ChenyangSi/FreeU)。

#### diffusers.StableDiffusionMixin.disable_freeu[[diffusers.StableDiffusionMixin.disable_freeu]]

```python
diffusers.StableDiffusionMixin.disable_freeu()
```

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

如果已启用，则禁用 FreeU 机制。

## PushToHubMixin[[diffusers.utils.PushToHubMixin]]

#### diffusers.utils.PushToHubMixin[[diffusers.utils.PushToHubMixin]]

```python
diffusers.utils.PushToHubMixin()
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/utils/hub_utils.py#L491)

一个用于将模型、调度器或流水线推送到 Hugging Face Hub 的 Mixin。

#### push_to_hub[[diffusers.utils.PushToHubMixin.push_to_hub]]

```python
push_to_hub(repo_id: str, commit_message: str | None = None, private: bool | None = None, token: str | None = None, create_pr: bool = False, safe_serialization: bool = True, variant: str | None = None, subfolder: str | None = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/utils/hub_utils.py#L526)

**参数：**

repo_id (`str`) : 要推送模型、调度器或流水线文件的目标仓库名称。推送到组织时，应包含组织名称。`repo_id` 也可以是本地目录的路径。

commit_message (`str`, *可选*) : 推送时提交的说明信息。默认为 `"Upload {object}"`。

private (`bool`，*可选*)：是否将仓库设为私有。如果为 `None`（默认值），除非组织的默认设置为私有，否则仓库将是公开的。如果仓库已存在，则忽略此值。

token (`str`, *可选*) : 用于远程文件的 HTTP bearer 授权令牌。该令牌是在运行 `hf auth login` 时生成的（存储在 `~/.huggingface` 中）。

create_pr (`bool`，*可选*，默认为 `False`)：是否使用上传的文件创建 PR，还是直接提交。

safe_serialization (`bool`，*可选*，默认为 `True`)：是否将模型权重转换为 `safetensors` 格式。

variant (`str`, *可选*) : 如果指定，权重将以 `pytorch_model.<variant>.bin` 格式保存。

将模型、调度器或流水线文件上传到 🤗 Hugging Face Hub。

示例：

```python
from diffusers import UNet2DConditionModel

unet = UNet2DConditionModel.from_pretrained("stabilityai/stable-diffusion-2", subfolder="unet")

# Push the `unet` to your namespace with the name "my-finetuned-unet".
unet.push_to_hub("my-finetuned-unet")

# Push the `unet` to an organization with the name "my-finetuned-unet".
unet.push_to_hub("your-org/my-finetuned-unet")
```

## 回调[[diffusers.callbacks.PipelineCallback]]

#### diffusers.callbacks.PipelineCallback[[diffusers.callbacks.PipelineCallback]]

```python
diffusers.callbacks.PipelineCallback(cutoff_step_ratio = 1.0, cutoff_step_index = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/callbacks.py#L7)

所有在 pipeline 中使用的官方回调的基类。该类为自定义回调的实现提供了结构，并确保所有回调具有一致的接口。

请实现以下内容：`tensor_inputs`：此方法应返回一个列表，其中包含特定于您的回调的张量输入。您只能包含流水线类中 `._callback_tensor_inputs` 属性里列出的变量。`callback_fn`：此方法定义了您的回调的核心功能。

#### diffusers.callbacks.SDCFGCutoffCallback[[diffusers.callbacks.SDCFGCutoffCallback]]

```python
diffusers.callbacks.SDCFGCutoffCallback(cutoff_step_ratio = 1.0, cutoff_step_index = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/callbacks.py#L69)

Stable Diffusion 管道的回调函数。在达到特定步数（由 `cutoff_step_ratio` 或 `cutoff_step_index` 设置）后，此回调将禁用 CFG。

注意：此回调会通过在截止步骤后将 `_guidance_scale` 属性更改为 0.0 来修改流水线。

#### diffusers.callbacks.SDXLCFGCutoffCallback[[diffusers.callbacks.SDXLCFGCutoffCallback]]

```python
diffusers.callbacks.SDXLCFGCutoffCallback(cutoff_step_ratio = 1.0, cutoff_step_index = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/callbacks.py#L98)

基础 Stable Diffusion XL 管道的回调函数。在达到特定步数（由 `cutoff_step_ratio` 或 `cutoff_step_index` 设置）后，此回调将禁用 CFG。

注意：此回调会通过在截止步骤后将 `_guidance_scale` 属性更改为 0.0 来修改流水线。

#### diffusers.callbacks.SDXLControlnetCFGCutoffCallback[[diffusers.callbacks.SDXLControlnetCFGCutoffCallback]]

```python
diffusers.callbacks.SDXLControlnetCFGCutoffCallback(cutoff_step_ratio = 1.0, cutoff_step_index = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/callbacks.py#L140)

Controlnet Stable Diffusion XL 管道的回调函数。在达到特定步数（由 `cutoff_step_ratio` 或 `cutoff_step_index` 设置）后，此回调将禁用 CFG。

注意：此回调会通过在截止步骤后将 `_guidance_scale` 属性更改为 0.0 来修改流水线。

#### diffusers.callbacks.IPAdapterScaleCutoffCallback[[diffusers.callbacks.IPAdapterScaleCutoffCallback]]

```python
diffusers.callbacks.IPAdapterScaleCutoffCallback(cutoff_step_ratio = 1.0, cutoff_step_index = None)
```

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

适用于任何继承自 `IPAdapterMixin` 的 pipeline 的回调函数。在达到特定步数（由 `cutoff_step_ratio` 或 `cutoff_step_index` 设置）后，此回调会将 IP Adapter 的 scale 设置为 `0.0`。

注意：此回调会在 cutoff 步骤之后将 IP Adapter 注意力处理器的 scale 设置为 0.0，从而修改这些处理器。

#### diffusers.callbacks.SD3CFGCutoffCallback[[diffusers.callbacks.SD3CFGCutoffCallback]]

```python
diffusers.callbacks.SD3CFGCutoffCallback(cutoff_step_ratio = 1.0, cutoff_step_index = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/callbacks.py#L212)

Stable Diffusion 3 管道的回调函数。在达到特定步数（由 `cutoff_step_ratio` 或 `cutoff_step_index` 设置）后，此回调将禁用 CFG。

注意：此回调会通过在截止步骤后将 `_guidance_scale` 属性更改为 0.0 来修改流水线。

