# DDPMScheduler

Jonathan Ho、Ajay Jain 和 Pieter Abbeel 提出的 [Denoising Diffusion Probabilistic Models](https://huggingface.co/papers/2006.11239)（DDPM）提出了一种同名的基于扩散的模型。在 🤗 Diffusers 库的语境中，DDPM 既指代论文中的离散去噪调度器，也指代相应的 pipeline。

该论文的摘要如下：

*我们展示了使用扩散概率模型（一类受非平衡热力学启发的隐变量模型）进行高质量图像合成的结果。我们的最佳结果是通过在根据扩散概率模型与朗之万动力学去噪分数匹配之间新发现的联系而设计的加权变分界上训练获得的，并且我们的模型自然地支持一种渐进式有损解压方案，该方案可被解释为自回归解码的推广。在无条件的 CIFAR10 数据集上，我们获得了 9.46 的 Inception 分数和 3.17 的 FID 分数，达到了当前最优水平。在 256x256 LSUN 上，我们获得了与 ProgressiveGAN 相似的样本质量。我们的实现可在 [this https URL](https://github.com/hojonathanho/diffusion) 获取。*

## DDPMScheduler[[diffusers.DDPMScheduler]]

#### diffusers.DDPMScheduler[[diffusers.DDPMScheduler]]

```python
diffusers.DDPMScheduler(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', 'sigmoid'] = 'linear', trained_betas: numpy.ndarray | list[float] | None = None, variance_type: typing.Literal['fixed_small', 'fixed_small_log', 'fixed_large', 'fixed_large_log', 'learned', 'learned_range'] = 'fixed_small', clip_sample: bool = True, prediction_type: typing.Literal['epsilon', 'sample', 'v_prediction'] = 'epsilon', thresholding: bool = False, dynamic_thresholding_ratio: float = 0.995, clip_sample_range: float = 1.0, sample_max_value: float = 1.0, timestep_spacing: typing.Literal['linspace', 'leading', 'trailing'] = 'leading', steps_offset: int = 0, rescale_betas_zero_snr: bool = False)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/schedulers/scheduling_ddpm.py#L137)

**参数：**

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"` 或 `"sigmoid"`，默认为 `"linear"`)：beta 调度，即将 beta 范围映射为用于模型步进的一系列 beta 值。

trained_betas (`np.ndarray`, *可选*) : 一个 beta 数组，用于直接传递给构造函数，而无需使用 `beta_start` 和 `beta_end`。

variance_type (`"fixed_small"`、`"fixed_small_log"`、`"fixed_large"`、`"fixed_large_log"`、`"learned"` 或 `"learned_range"`，默认为 `"fixed_small"`)：在向去噪样本添加噪声时，对方差进行裁剪。

clip_sample (`bool`，默认为 `True`)：对预测样本进行裁剪，以确保数值稳定性。

clip_sample_range (`float`，默认为 `1.0`)：样本裁剪的最大幅度。仅在 `clip_sample=True` 时有效。

prediction_type (`"epsilon"`, `"sample"`, or `"v_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`) or `v_prediction` (see section 2.4 of [Imagen Video](https://huggingface.co/papers/2210.02303) paper).

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

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

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

timestep_spacing (`"linspace"`, `"leading"`, or `"trailing"`, defaults to `"leading"`) : The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information.

steps_offset (`int`，默认为 `0`)：添加到推理步数中的偏移量，某些模型系列需要此参数。

rescale_betas_zero_snr (`bool`，默认为 `False`)：是否将 betas 重新缩放，使其具有零终端 SNR。这使模型能够生成非常明亮和非常暗的样本，而不是将其限制在中等亮度的样本上。与 [`--offset_noise`](https://github.com/huggingface/diffusers/blob/74fd735eb073eb1d774b1ab4154a0876eb82f055/examples/dreambooth/train_dreambooth.py#L506) 大致相关。

`DDPMScheduler` 探索了去噪分数匹配与朗之万动力学采样之间的联系。

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

#### add_noise[[diffusers.DDPMScheduler.add_noise]]

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

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/schedulers/scheduling_ddpm.py#L569)

**参数：**

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

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

timesteps (`torch.IntTensor`)：指示每个样本噪声水平的时间步。

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

带噪声的样本。

根据每个时间步的噪声幅度，向原始样本添加噪声（即前向扩散过程）。

#### get_velocity[[diffusers.DDPMScheduler.get_velocity]]

```python
get_velocity(sample: Tensor, noise: Tensor, timesteps: IntTensor)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/schedulers/scheduling_ddpm.py#L611)

**参数：**

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

noise (`torch.Tensor`) : 噪声张量。

timesteps (`torch.IntTensor`)：用于速度计算的 timesteps。

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

计算得到的速度。

根据速度公式，从样本和噪声计算速度预测。

#### previous_timestep[[diffusers.DDPMScheduler.previous_timestep]]

```python
previous_timestep(timestep: int)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/schedulers/scheduling_ddpm.py#L648)

**参数：**

timestep (`int`)：当前时间步。

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

上一个时间步。

计算扩散链中的前一个时间步。

#### scale_model_input[[diffusers.DDPMScheduler.scale_model_input]]

```python
scale_model_input(sample: Tensor, timestep: int | None = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/schedulers/scheduling_ddpm.py#L257)

**参数：**

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

timestep (`int`, *可选*) : 扩散链中的当前时间步。

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

经过缩放的输入样本。

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

#### set_timesteps[[diffusers.DDPMScheduler.set_timesteps]]

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

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/schedulers/scheduling_ddpm.py#L274)

**参数：**

num_inference_steps (`int`, *可选*) : 使用预训练模型生成样本时所用的扩散步数。如果使用了该参数，`timesteps` 必须为 `None`。

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

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

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

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

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

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/schedulers/scheduling_ddpm.py#L461)

**参数：**

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

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

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

generator (`torch.Generator`, *可选*) : 随机数生成器。

return_dict (`bool`，默认为 `True`)：是否返回 [DDPMSchedulerOutput](/docs/diffusers/main/zh/api/schedulers/ddpm#diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput) 或 `tuple`。

**返回：** [DDPMSchedulerOutput](/docs/diffusers/main/zh/api/schedulers/ddpm#diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput) 或 `tuple`

If return_dict is `True`, [DDPMSchedulerOutput](/docs/diffusers/main/zh/api/schedulers/ddpm#diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput) is returned, otherwise a tuple is returned where the first element is the sample tensor.

通过逆向 SDE 预测上一时间步的样本。此函数将扩散过程从学习到的模型输出（通常是预测的噪声）进行传播。

## DDPMSchedulerOutput[[diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput]]

#### diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput[[diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput]]

```python
diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput(prev_sample: Tensor, pred_original_sample: typing.Optional[torch.Tensor] = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/schedulers/scheduling_ddpm.py#L31)

**参数：**

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

pred_original_sample （对于图像，形状为 `(batch_size, num_channels, height, width)` 的 `torch.Tensor`）：基于当前时间步的模型输出预测的去噪样本 `(x_{0})`。`pred_original_sample` 可用于预览进度或进行引导。

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

