# DPMSolverSinglestepScheduler

`DPMSolverSinglestepScheduler` 是 Cheng Lu、Yuhao Zhou、Fan Bao、Jianfei Chen、Chongxuan Li 和 Jun Zhu 在 [DPM-Solver: A Fast ODE Solver for Diffusion Probabilistic Model Sampling in Around 10 Steps](https://huggingface.co/papers/2206.00927) 和 [DPM-Solver++: Fast Solver for Guided Sampling of Diffusion Probabilistic Models](https://huggingface.co/papers/2211.01095) 中提出的单步调度器。

DPMSolver （以及改进版本 DPMSolver++）是一种专为扩散 ODE 设计的高阶快速求解器，具有收敛阶数保证。经验上，DPMSolver 采样仅需 20 步即可生成高质量样本，即使在 10 步内也能生成相当不错的样本。

原始实现可在 [LuChengTHU/dpm-solver](https://github.com/LuChengTHU/dpm-solver) 中找到。

## 提示

建议将 `solver_order` 设置为 2 用于引导采样，将 `solver_order=3` 用于无条件采样。

支持来自 [Imagen](https://huggingface.co/papers/2205.11487) 的动态阈值处理。对于像素空间扩散模型，您可以同时设置 `algorithm_type="dpmsolver++"` 和 `thresholding=True` 以使用动态阈值处理。此阈值处理方法不适用于 Stable Diffusion 等潜在空间扩散模型。

## DPMSolverSinglestepScheduler[[diffusers.DPMSolverSinglestepScheduler]]

#### diffusers.DPMSolverSinglestepScheduler[[diffusers.DPMSolverSinglestepScheduler]]

```python
diffusers.DPMSolverSinglestepScheduler(num_train_timesteps: int = 1000, beta_start: float = 0.0001, beta_end: float = 0.02, beta_schedule: typing.Literal['linear', 'scaled_linear', 'squaredcos_cap_v2'] = 'linear', trained_betas: numpy.ndarray | list[float] | None = None, solver_order: int = 2, prediction_type: typing.Literal['epsilon', 'sample', 'v_prediction', 'flow_prediction'] = 'epsilon', thresholding: bool = False, dynamic_thresholding_ratio: float = 0.995, sample_max_value: float = 1.0, algorithm_type: typing.Literal['dpmsolver', 'dpmsolver++', 'sde-dpmsolver++'] = 'dpmsolver++', solver_type: typing.Literal['midpoint', 'heun'] = 'midpoint', lower_order_final: bool = False, use_karras_sigmas: bool = False, use_exponential_sigmas: bool = False, use_beta_sigmas: bool = False, use_flow_sigmas: bool = False, flow_shift: float = 1.0, final_sigmas_type: typing.Literal['zero', 'sigma_min'] = 'zero', lambda_min_clipped: float = -inf, variance_type: typing.Optional[typing.Literal['learned', 'learned_range']] = None, use_dynamic_shifting: bool = False, time_shift_type: typing.Literal['exponential'] = 'exponential')
```

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

**参数：**

num_train_timesteps (`int`，默认为 `1000`)：用于训练模型的扩散步数。

beta_start (`float`，默认值为 `0.0001`)：推理的初始 `beta` 值。

beta_end (`float`，默认值为 `0.02`)：最终的 `beta` 值。

beta_schedule (`"linear"`、`"scaled_linear"` 或 `"squaredcos_cap_v2"`，默认为 `"linear"`)：beta 调度，即将 beta 范围映射为用于模型步进的一系列 beta 值。可选 `linear`、`scaled_linear` 或 `squaredcos_cap_v2`。

trained_betas (`np.ndarray` 或 `list[float]`，*可选*) : 直接传入 betas 数组以绕过 `beta_start` 和 `beta_end`。

solver_order (`int`，默认为 `2`)：DPMSolver 的阶数，可以是 `1`、`2` 或 `3`。建议在有引导采样时使用 `solver_order=2`，在无引导采样时使用 `solver_order=3`。

prediction_type (`"epsilon"`, `"sample"`, `"v_prediction"`, or `"flow_prediction"`, defaults to `"epsilon"`) : Prediction type of the scheduler function; can be `epsilon` (predicts the noise of the diffusion process), `sample` (directly predicts the noisy sample`), `v_prediction` (see section 2.4 of [Imagen Video](https://huggingface.co/papers/2210.02303) paper), or `flow_prediction`.

thresholding (`bool`，默认为 `False`)：是否使用“动态阈值”方法。此方法不适用于 Stable Diffusion 等潜在空间扩散模型。

dynamic_thresholding_ratio (`float`，默认为 `0.995`)：动态阈值化方法的比例。仅在 `thresholding=True` 时有效。

sample_max_value (`float`，默认为 `1.0`)：动态阈值化的阈值。仅在 `thresholding=True` 且 `algorithm_type="dpmsolver++"` 时有效。

algorithm_type (`"dpmsolver"`、`"dpmsolver++"` 或 `"sde-dpmsolver++"`，默认为 `"dpmsolver++"`)：求解器的算法类型；可以是 `dpmsolver`、`dpmsolver++` 或 `sde-dpmsolver++`。`dpmsolver` 类型实现了 [DPMSolver](https://huggingface.co/papers/2206.00927) 论文中的算法，而 `dpmsolver++` 类型实现了 [DPMSolver++](https://huggingface.co/papers/2211.01095) 论文中的算法。对于 Stable Diffusion 中的引导采样，建议使用 `dpmsolver++` 或 `sde-dpmsolver++` 并设置 `solver_order=2`。

solver_type (`"midpoint"` 或 `"heun"`，默认为 `"midpoint"`)：二阶求解器的求解器类型；可以是 `midpoint` 或 `heun`。求解器类型会轻微影响样本质量，尤其是在步数较少时。建议使用 `midpoint` 求解器。

lower_order_final (`bool`，默认为 `False`)：是否在最后几步中使用低阶求解器。仅对少于 15 个推理步骤有效。这可以稳定 DPMSolver 在少于 15 步时的采样，尤其是在 10 步及以下的情况下。

use_karras_sigmas (`bool`，*可选*，默认为 `False`)：是否在采样过程的噪声调度中使用 Karras sigmas 作为步长。如果为 `True`，则 sigmas 将根据噪声水平序列 {σi} 确定。

use_exponential_sigmas (`bool`，*可选*，默认为 `False`)：在采样过程中，噪声调度是否使用指数 sigma 作为步长。

use_beta_sigmas (`bool`, *optional*, defaults to `False`) : Whether to use beta sigmas for step sizes in the noise schedule during the sampling process. Refer to [Beta Sampling is All You Need](https://huggingface.co/papers/2407.12173) for more information.

use_flow_sigmas (`bool`，*可选*，默认为 `False`)：是否在采样过程的噪声调度中使用 flow sigmas 作为步长。

flow_shift (`float`, *可选*，默认为 `1.0`)：基于流的模型的 flow shift 参数。

final_sigmas_type (`"zero"` 或 `"sigma_min"`，*可选*，默认为 `"zero"`)：采样过程中噪声调度的最终 `sigma` 值。如果为 `"sigma_min"`，则最终 sigma 与训练调度中的最后一个 sigma 相同。如果为 `"zero"`，则最终 sigma 设为 0。

lambda_min_clipped (`float`，默认为 `-inf`)：`lambda(t)` 最小值的裁剪阈值，用于保证数值稳定性。这对于余弦（`squaredcos_cap_v2`）噪声调度至关重要。

variance_type (`"learned"` 或 `"learned_range"`，*可选*)：对于预测方差的扩散模型，设置为 `"learned"` 或 `"learned_range"`。如果设置，模型的输出将包含预测的高斯方差。

use_dynamic_shifting (`bool`，默认为 `False`)：是否对噪声调度使用动态偏移。

time_shift_type (`"exponential"`，默认为 `"exponential"`)：要应用的时间偏移类型。

`DPMSolverSinglestepScheduler` 是一种专为扩散 ODE 设计的高效高阶求解器。

该模型继承自 [SchedulerMixin](/docs/diffusers/v0.43.0/zh/api/schedulers/overview#diffusers.SchedulerMixin) 和 [ConfigMixin](/docs/diffusers/v0.43.0/zh/api/configuration#diffusers.ConfigMixin)。有关该库为所有调度器实现的通用方法（例如加载和保存），请参阅父类文档。

#### add_noise[[diffusers.DPMSolverSinglestepScheduler.add_noise]]

```python
add_noise(original_samples: Tensor, noise: Tensor, timesteps: IntTensor)
```

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

**参数：**

original_samples (`torch.Tensor`) : 未添加噪声的原始样本。

noise (`torch.Tensor`) : 要添加到样本中的噪声。

timesteps (`torch.IntTensor`) : 向样本添加噪声的时间步。

**返回：** `torch.Tensor`

带噪声的样本。

根据指定时间步的噪声调度，向原始样本添加噪声。

#### convert_model_output[[diffusers.DPMSolverSinglestepScheduler.convert_model_output]]

```python
convert_model_output(model_output: Tensor, *args, sample: typing.Optional[torch.Tensor] = None, **kwargs)
```

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

**参数：**

model_output (`torch.Tensor`)：学习到的扩散模型的直接输出。

sample (`torch.Tensor`)：扩散过程生成的当前样本实例。

**返回：** `torch.Tensor`

转换后的模型输出。

将模型输出转换为 DPMSolver/DPMSolver++ 算法所需的对应类型。DPM-Solver 旨在对噪声预测模型的积分进行离散化，而 DPM-Solver++ 则旨在对数据预测模型的积分进行离散化。

> [!TIP] > 算法和模型类型是解耦的。您可以使用 DPMSolver 或 DPMSolver++ 来
噪声 > 预测和数据预测模型。

#### dpm_solver_first_order_update[[diffusers.DPMSolverSinglestepScheduler.dpm_solver_first_order_update]]

```python
dpm_solver_first_order_update(model_output: Tensor, *args, sample: typing.Optional[torch.Tensor] = None, noise: typing.Optional[torch.Tensor] = None, **kwargs)
```

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

**参数：**

model_output (`torch.Tensor`)：学习到的扩散模型的直接输出。

timestep (`int`)：扩散链中当前的离散时间步。

prev_timestep (`int`) : 扩散链中的上一个离散时间步。

sample (`torch.Tensor`)：扩散过程生成的当前样本实例。

noise (`torch.Tensor`, *可选*) : 随机噪声，用于随机 (`sde-*`) 求解器变体。当 `algorithm_type` 设置为其中一种时必填，否则不使用。

**返回：** `torch.Tensor`

上一步时间步的样本张量。

一阶 DPMSolver 的一步（等效于 DDIM）。

#### get_order_list[[diffusers.DPMSolverSinglestepScheduler.get_order_list]]

```python
get_order_list(num_inference_steps: int)
```

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

**参数：**

num_inference_steps (`int`) : 使用预训练模型生成样本时所用的扩散步数。

**返回：** `list[int]`

每个时间步的求解器阶数列表。

计算每个时间步的求解器阶数。

#### index_for_timestep[[diffusers.DPMSolverSinglestepScheduler.index_for_timestep]]

```python
index_for_timestep(timestep: typing.Union[int, torch.Tensor], schedule_timesteps: typing.Optional[torch.Tensor] = None)
```

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

**参数：**

timestep (`int` 或 `torch.Tensor`)：用于查找索引的时间步。

schedule_timesteps (`torch.Tensor`, *可选*) : 要搜索的时间步调度。如果为 `None`，则使用 `self.timesteps`。

**返回值：** `int`

时间步在调度器中的索引。

查找给定时间步在调度器中的索引。

#### scale_model_input[[diffusers.DPMSolverSinglestepScheduler.scale_model_input]]

```python
scale_model_input(sample: Tensor, *args, **kwargs)
```

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

**参数：**

sample (`torch.Tensor`)：输入样本。

**返回：** `torch.Tensor`

经过缩放的输入样本。

确保与那些需要根据当前时间步对去噪模型输入进行缩放的调度器保持可互换性。

#### set_begin_index[[diffusers.DPMSolverSinglestepScheduler.set_begin_index]]

```python
set_begin_index(begin_index: int = 0)
```

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

**参数：**

begin_index (`int`，默认为 `0`)：调度器的起始索引。

设置调度器的起始索引。此函数应在推理之前从流水线中运行。

#### set_timesteps[[diffusers.DPMSolverSinglestepScheduler.set_timesteps]]

```python
set_timesteps(num_inference_steps: int = None, device: typing.Union[str, torch.device] = None, mu: float | None = None, timesteps: list[int] | None = None)
```

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

**参数：**

num_inference_steps (`int`, *可选*)：使用预训练模型生成样本时所用的扩散步数。

device (`str` 或 `torch.device`，*可选*)：时间步应移动到的设备。如果为 `None`，则不移动时间步。

mu (`float`, *可选*) : 动态时间平移的指数。需要 `use_dynamic_shifting` 且 `time_shift_type` 为 `"exponential"`；传入时，`flow_shift` 将被设置为 `exp(mu)`。

timesteps (`list[int]`, *可选*) : 用于支持任意时间步间隔的自定义时间步。如果为 `None`，则使用默认的时间步间隔策略，即在时间步调度中采用等间隔。如果传入了 `timesteps`，则 `num_inference_steps` 必须为 `None`。

设置扩散链所使用的离散时间步（需在推理之前运行）。

#### singlestep_dpm_solver_second_order_update[[diffusers.DPMSolverSinglestepScheduler.singlestep_dpm_solver_second_order_update]]

```python
singlestep_dpm_solver_second_order_update(model_output_list: list[torch.Tensor], *args, sample: typing.Optional[torch.Tensor] = None, noise: typing.Optional[torch.Tensor] = None, **kwargs)
```

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

**参数：**

model_output_list (`list[torch.Tensor]`) : 学习到的扩散模型在当前及后续时间步的直接输出。

timestep (`int`) : 扩散链中的当前及后续离散时间步。

prev_timestep (`int`) : 扩散链中的上一个离散时间步。

sample (`torch.Tensor`)：扩散过程生成的当前样本实例。

noise (`torch.Tensor`, *可选*) : 随机噪声，用于随机 (`sde-*`) 求解器变体。当 `algorithm_type` 设置为其中一种时必填，否则不使用。

**返回：** `torch.Tensor`

上一步时间步的样本张量。

用于二阶单步 DPMSolver 的一步，从时间 `timestep_list[-2]` 计算时间 `prev_timestep` 处的解。

#### singlestep_dpm_solver_third_order_update[[diffusers.DPMSolverSinglestepScheduler.singlestep_dpm_solver_third_order_update]]

```python
singlestep_dpm_solver_third_order_update(model_output_list: list[torch.Tensor], *args, sample: typing.Optional[torch.Tensor] = None, noise: typing.Optional[torch.Tensor] = None, **kwargs)
```

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

**参数：**

model_output_list (`list[torch.Tensor]`) : 学习到的扩散模型在当前及后续时间步的直接输出。

timestep (`int`) : 扩散链中的当前及后续离散时间步。

prev_timestep (`int`) : 扩散链中的上一个离散时间步。

sample (`torch.Tensor`)：扩散过程创建的当前样本实例。

noise (`torch.Tensor`, *可选*) : 随机噪声，用于随机 (`sde-*`) 求解器变体。当 `algorithm_type` 设置为其中一种时必填，否则不使用。

**返回：** `torch.Tensor`

上一步时间步的样本张量。

这是三阶单步 DPMSolver 的一步，用于从时间 `timestep_list[-3]` 计算时间 `prev_timestep` 处的解。

#### singlestep_dpm_solver_update[[diffusers.DPMSolverSinglestepScheduler.singlestep_dpm_solver_update]]

```python
singlestep_dpm_solver_update(model_output_list: list[torch.Tensor], *args, sample: typing.Optional[torch.Tensor] = None, order: int = None, noise: typing.Optional[torch.Tensor] = None, **kwargs)
```

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

**参数：**

model_output_list (`list[torch.Tensor]`) : 学习到的扩散模型在当前及后续时间步的直接输出。

timestep (`int`) : 扩散链中的当前及后续离散时间步。

prev_timestep (`int`) : 扩散链中的上一个离散时间步。

sample (`torch.Tensor`)：扩散过程创建的当前样本实例。

order (`int`) : 此步骤的求解器阶数。

noise (`torch.Tensor`, *可选*) : 随机噪声，用于随机 (`sde-*`) 求解器变体。当 `algorithm_type` 设置为其中一种时必填，否则不使用。

**返回：** `torch.Tensor`

上一步时间步的样本张量。

单步 DPMSolver 的一步。

#### 步骤[[diffusers.DPMSolverSinglestepScheduler.step]]

```python
step(model_output: Tensor, timestep: typing.Union[int, torch.Tensor], sample: Tensor, generator: typing.Optional[torch.Generator] = None, return_dict: bool = True)
```

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

**参数：**

model_output (`torch.Tensor`)：学习到的扩散模型的直接输出。

timestep (`int` 或 `torch.Tensor`)：扩散链中当前的离散时间步。

sample (`torch.Tensor`)：扩散过程生成的当前样本实例。

generator (`torch.Generator`, *可选*) : 用于随机采样的随机数生成器。

return_dict (`bool`，默认为 `True`)：是否返回 [SchedulerOutput](/docs/diffusers/v0.43.0/zh/api/schedulers/ipndm#diffusers.schedulers.scheduling_utils.SchedulerOutput) 或 `tuple`。

**返回：** [SchedulerOutput](/docs/diffusers/v0.43.0/zh/api/schedulers/ipndm#diffusers.schedulers.scheduling_utils.SchedulerOutput) 或 `tuple`

If return_dict is `True`, [SchedulerOutput](/docs/diffusers/v0.43.0/zh/api/schedulers/ipndm#diffusers.schedulers.scheduling_utils.SchedulerOutput) is returned, otherwise a tuple is returned where the first element is the sample tensor.

通过反转 SDE 来预测上一步时间步的样本。此函数使用 singlestep DPMSolver 传播样本。

## SchedulerOutput[[diffusers.schedulers.scheduling_utils.SchedulerOutput]]

#### diffusers.schedulers.scheduling_utils.SchedulerOutput[[diffusers.schedulers.scheduling_utils.SchedulerOutput]]

```python
diffusers.schedulers.scheduling_utils.SchedulerOutput(prev_sample: Tensor)
```

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

**参数：**

prev_sample （对于图像，形状为 `(batch_size, num_channels, height, width)` 的 `torch.Tensor`）：计算得到的前一时间步的样本 `(x_{t-1})`。在去噪循环中，应将 `prev_sample` 用作下一个模型输入。

调度器 `step` 函数输出的基类。

