# KDPM2AncestralDiscreteScheduler

The `KDPM2DiscreteScheduler` with ancestral sampling is inspired by the [Elucidating the Design Space of Diffusion-Based Generative Models](https://huggingface.co/papers/2206.00364) paper, and the scheduler is ported from and created by [Katherine Crowson](https://github.com/crowsonkb/).

原始代码库可在 [crowsonkb/k-diffusion](https://github.com/crowsonkb/k-diffusion) 中找到。

## KDPM2AncestralDiscreteScheduler[[diffusers.KDPM2AncestralDiscreteScheduler]]

#### diffusers.KDPM2AncestralDiscreteScheduler[[diffusers.KDPM2AncestralDiscreteScheduler]]

```python
diffusers.KDPM2AncestralDiscreteScheduler(num_train_timesteps: int = 1000, beta_start: float = 0.00085, beta_end: float = 0.012, beta_schedule: str = 'linear', trained_betas: numpy.ndarray | list[float] | None = None, use_karras_sigmas: bool = False, use_exponential_sigmas: bool = False, use_beta_sigmas: bool = False, prediction_type: str = 'epsilon', timestep_spacing: str = 'linspace', steps_offset: int = 0)
```

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

**参数：**

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

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

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

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

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

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

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

use_beta_sigmas (`bool`, 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.

prediction_type (`str`, 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).

timestep_spacing (`str`, defaults to `"linspace"`) : 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)：根据某些模型系列的要求，添加到推理步数中的偏移量。

KDPM2DiscreteScheduler with ancestral sampling is inspired by the DPMSolver2 and Algorithm 2 from the [Elucidating the Design Space of Diffusion-Based Generative Models](https://huggingface.co/papers/2206.00364) paper.

该模型继承自 [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.KDPM2AncestralDiscreteScheduler.add_noise]]

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

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

**参数：**

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

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

timesteps (`torch.Tensor`) : 添加噪声的时间步，用于从调度器中确定噪声水平。

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

根据时间步调度对添加的噪声进行缩放后的含噪样本。

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

#### index_for_timestep[[diffusers.KDPM2AncestralDiscreteScheduler.index_for_timestep]]

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

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

**参数：**

timestep (`float` 或 `torch.Tensor`)：要在调度器中查找的时间步值。

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

**返回值：** `int`

时间步在调度器中的索引。对于第一步，如果存在多个匹配项，则返回第二个索引，以避免在从调度器中间开始（例如，用于图像到图像任务）时跳过某个 sigma。

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

#### scale_model_input[[diffusers.KDPM2AncestralDiscreteScheduler.scale_model_input]]

```python
scale_model_input(sample: Tensor, timestep: typing.Union[float, torch.Tensor])
```

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

**参数：**

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

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

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

经过缩放的输入样本。

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

#### set_begin_index[[diffusers.KDPM2AncestralDiscreteScheduler.set_begin_index]]

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

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

**参数：**

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

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

#### set_timesteps[[diffusers.KDPM2AncestralDiscreteScheduler.set_timesteps]]

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

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

**参数：**

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

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

num_train_timesteps (`int`，*可选*)：用于训练模型的扩散步数。如果为 `None`，则使用 `self.config.num_train_timesteps`。

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

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

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

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

**参数：**

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

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

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

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

return_dict (`bool`，默认为 `True`)：是否返回 `KDPM2AncestralDiscreteSchedulerOutput` 或元组。

**返回值：**

`KDPM2AncestralDiscreteSchedulerOutput` 或 `tuple[torch.Tensor, torch.Tensor]`：如果 `return_dict` 为 `True`，则返回 `KDPM2AncestralDiscreteSchedulerOutput`，否则返回一个元组，其中第一个元素为样本张量。

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

## 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` 函数输出的基类。

