# EulerDiscreteScheduler

Euler 调度器（算法 2）出自 Karras 等人撰写的论文 [Elucidating the Design Space of Diffusion-Based Generative Models](https://huggingface.co/papers/2206.00364)。这是一种快速调度器，通常能在 20-30 步内生成良好的输出。该调度器基于 [Katherine Crowson](https://github.com/crowsonkb/) 最初的 [k-diffusion](https://github.com/crowsonkb/k-diffusion/blob/481677d114f6ea445aa009cf5bd7a9cdee909e47/k_diffusion/sampling.py#L51) 实现。

## EulerDiscreteScheduler[[diffusers.EulerDiscreteScheduler]]

#### diffusers.EulerDiscreteScheduler[[diffusers.EulerDiscreteScheduler]]

```python
diffusers.EulerDiscreteScheduler(num_train_timesteps: int = 1000, beta_start: float = 0.0001, beta_end: float = 0.02, beta_schedule: str = 'linear', trained_betas: numpy.ndarray | list[float] | None = None, prediction_type: str = 'epsilon', interpolation_type: str = 'linear', use_karras_sigmas: bool | None = False, use_exponential_sigmas: bool | None = False, use_beta_sigmas: bool | None = False, sigma_min: float | None = None, sigma_max: float | None = None, timestep_spacing: typing.Literal['linspace', 'leading', 'trailing'] = 'linspace', timestep_type: typing.Literal['discrete', 'continuous'] = 'discrete', steps_offset: int = 0, rescale_betas_zero_snr: bool = False, final_sigmas_type: typing.Literal['zero', 'sigma_min'] = 'zero')
```

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

**参数：**

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

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

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

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

trained_betas (`np.ndarray`，*可选*)：将 beta 数组直接传递给构造函数，以绕过 `beta_start` 和 `beta_end`。

prediction_type (`Literal["epsilon", "sample", "v_prediction"]`, defaults to `"epsilon"`, *optional*) : 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).

interpolation_type (`Literal["linear", "log_linear"]`，默认为 `"linear"`，*可选*)：用于计算调度器去噪步骤中间 sigma 值的插值类型。应为 `"linear"` 或 `"log_linear"` 之一。

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.

sigma_min (`float`, *可选*) : 噪声调度的最小 sigma 值。如果未提供，则默认为调度中的最后一个 sigma。

sigma_max (`float`, *可选*) : 噪声调度的最大 sigma 值。如果未提供，则默认为调度中的第一个 sigma。

timestep_spacing (`Literal["linspace", "leading", "trailing"]`，默认为 `"linspace"`)：时间步的缩放方式。更多信息请参阅 [《常见的扩散噪声调度和采样步骤存在缺陷》](https://huggingface.co/papers/2305.08891) 中的表 2。

timestep_type (`Literal["discrete", "continuous"]`，默认为 `"discrete"`)：要使用的时间步类型。可以是 `"discrete"` 或 `"continuous"`。

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) 大致相关。

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

Euler 调度器。

该模型继承自 [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.EulerDiscreteScheduler.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_euler_discrete.py#L802)

**参数：**

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

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

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

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

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

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

#### get_velocity[[diffusers.EulerDiscreteScheduler.get_velocity]]

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

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

**参数：**

sample (`torch.Tensor`) : 用于计算速度的输入样本。

noise (`torch.Tensor`) : 与样本对应的噪声张量。

timesteps (`torch.Tensor`) : 用于计算速度的时间步。

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

计算得到的速度预测为 `sqrt(alpha_prod) * noise - sqrt(1 - alpha_prod) * sample`。

在指定的时间步上，计算给定样本和噪声的速度预测。

该方法实现了 v-prediction 模型中使用的速度预测，它预测的是样本与噪声的线性组合。

#### index_for_timestep[[diffusers.EulerDiscreteScheduler.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_euler_discrete.py#L640)

**参数：**

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

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

**返回值：** `int`

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

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

#### scale_model_input[[diffusers.EulerDiscreteScheduler.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_euler_discrete.py#L326)

**参数：**

sample (`torch.Tensor`) : 待缩放的输入样本。

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

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

经过缩放的输入样本，除以 `(sigma**2 + 1) ** 0.5`。

确保与需要根据当前时间步缩放去噪模型输入的调度器具有互换性。将去噪模型输入按 `(sigma**2 + 1) ** 0.5` 进行缩放，以匹配 Euler 算法。

#### set_begin_index[[diffusers.EulerDiscreteScheduler.set_begin_index]]

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

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

**参数：**

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

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

#### set_timesteps[[diffusers.EulerDiscreteScheduler.set_timesteps]]

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

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

**参数：**

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

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

timesteps (`list[int]`, *可选*) : 用于支持任意时间步调度的自定义时间步。如果为 `None`，则基于 `timestep_spacing` 属性生成时间步。如果传入了 `timesteps`，则 `num_inference_steps` 和 `sigmas` 必须为 `None`，并且 `timestep_spacing` 属性将被忽略。

sigmas (`list[float]`, *可选*) : 用于支持任意时间步调度的自定义 sigmas。如果为 `None`，则时间步和 sigmas 将基于相关调度器属性生成。如果传入了 `sigmas`，则 `num_inference_steps` 和 `timesteps` 必须为 `None`，并且时间步将基于自定义 sigmas 调度生成。

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

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

```python
step(model_output: Tensor, timestep: typing.Union[float, torch.Tensor], sample: Tensor, s_churn: float = 0.0, s_tmin: float = 0.0, s_tmax: float = inf, s_noise: float = 1.0, generator: typing.Optional[torch.Generator] = None, return_dict: bool = True)
```

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

**参数：**

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

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

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

s_churn (`float`，*可选*，默认值为 `0.0`)：控制采样过程中添加噪声量的随机性参数。值越大，随机性越强。

s_tmin (`float`，*可选*，默认为 `0.0`)：应用随机性的最小时间步阈值。仅当时间步大于该值时才会添加噪声。

s_tmax (`float`，*可选*，默认为 `inf`)：应用随机性的最大时间步阈值。仅在此值以下的时间步会添加噪声。

s_noise (`float`, *可选*, 默认值为 `1.0`) : 添加到样本中的噪声的缩放因子。

generator (`torch.Generator`，*可选*)：用于可复现采样的随机数生成器。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 [EulerDiscreteSchedulerOutput](/docs/diffusers/v0.43.0/zh/api/schedulers/euler#diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput) 或元组。

**返回：** [EulerDiscreteSchedulerOutput](/docs/diffusers/v0.43.0/zh/api/schedulers/euler#diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput) 或 `tuple`

如果 `return_dict` 为 `True`，则返回 [EulerDiscreteSchedulerOutput](/docs/diffusers/v0.43.0/zh/api/schedulers/euler#diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput)；否则返回一个元组，其中第一个元素是样本张量，第二个元素是预测的原始样本。

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

## EulerDiscreteSchedulerOutput[[diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput]]

#### diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput[[diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput]]

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

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

**参数：**

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

