# UniPCMultistepScheduler

`UniPCMultistepScheduler` は、拡散モデルの高速サンプリングのために設計された、学習不要のフレームワークです。Wenliang Zhao、Lujia Bai、Yongming Rao、Jie Zhou、Jiwen Lu による [UniPC: A Unified Predictor-Corrector Framework for Fast Sampling of Diffusion Models](https://huggingface.co/papers/2302.04867) で提案されました。

UniPCは、統一された解析的な形式を共有し、任意の次数をサポートする補正器（UniC）と予測器（UniP）で構成されています。UniPCは設計上、モデルに依存せず、無条件/条件付きサンプリングにおけるピクセル空間/潜在空間のDPMをサポートします。また、ノイズ予測モデルとデータ予測モデルの両方に適用できます。補正器UniCは、市販のソルバーの後に適用して精度の次数を高めることも可能です。

論文の抄録は以下の通りです：

*拡散確率モデル（DPM）は、高解像度画像合成において非常に有望な能力を示しています。しかし、DPMからのサンプリングは、ノイズ除去ネットワークの複数回の評価が必要であるため時間がかかり、DPMのサンプリングを高速化することがますます重要になっています。高速サンプラーの設計における最近の進歩にもかかわらず、既存の方法では、より少ないステップ（例：<10）が好まれる多くのアプリケーションにおいて、満足できる画像を生成することが依然としてできません。本論文では、既存のDPMサンプラーの後に適用でき、追加のモデル評価なしで精度の次数を高めることができる統一コーレクター（UniC）を開発し、その副産物として、任意の次数をサポートする統一プレディクター（UniP）を導出します。UniPとUniCを組み合わせることで、DPMの高速サンプリングのための統一プレディクター-コーレクターフレームワークUniPCを提案します。UniPCは任意の次数に対して統一された解析的な形式を持ち、特に極めて少ないステップ数において、従来の手法よりもサンプリング品質を大幅に向上させることができます。ピクセル空間と潜在空間のDPMを用いた、無条件サンプリングと条件付きサンプリングの両方を含む広範な実験を通じて、我々の手法を評価しました。UniPCは、わずか10回の関数評価で、CIFAR10（無条件）でFID 3.87、ImageNet 256×256（条件付き）でFID 7.51を達成します。コードは[この https URL](https://github.com/wl-zhao/UniPC)で入手できます。*

## ヒント

ガイドサンプリングでは`solver_order`を2に設定すること、無条件サンプリングでは`solver_order=3`に設定することが推奨されます。

[Imagen](https://huggingface.co/papers/2205.11487)からの動的閾値化はサポートされており、ピクセル空間の拡散モデルでは、`predict_x0=True`と`thresholding=True`の両方を設定することで動的閾値化を使用できます。この閾値化手法は、Stable Diffusionなどの潜在空間拡散モデルには適していません。

## UniPCMultistepScheduler[[diffusers.UniPCMultistepScheduler]]

#### diffusers.UniPCMultistepScheduler[[diffusers.UniPCMultistepScheduler]]

```python
diffusers.UniPCMultistepScheduler(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, 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, predict_x0: bool = True, solver_type: typing.Literal['bh1', 'bh2'] = 'bh2', lower_order_final: bool = True, disable_corrector: list[int] = [], solver_p: SchedulerMixin = None, 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, timestep_spacing: typing.Literal['linspace', 'leading', 'trailing'] = 'linspace', steps_offset: int = 0, final_sigmas_type: typing.Literal['zero', 'sigma_min'] = 'zero', rescale_betas_zero_snr: bool = False, use_dynamic_shifting: bool = False, time_shift_type: typing.Literal['exponential'] = 'exponential', sigma_min: float | None = None, sigma_max: bool | None = None, shift_terminal: bool | None = None)
```

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/schedulers/scheduling_unipc_multistep.py#L123)

**パラメータ:**

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"`) : ベータスケジュール。ベータの範囲から、モデルのステップ処理に使用するベータのシーケンスへのマッピングです。`linear`、`scaled_linear`、または `squaredcos_cap_v2` から選択します。

trained_betas (`np.ndarray`、*任意*) : `beta_start` と `beta_end` をバイパスして、ベータの配列を直接コンストラクタに渡す。

solver_order (`int`、デフォルトは `2`) : UniPC の order を指定します。正の整数であれば何でも指定できます。UniC により、実際の精度の order は `solver_order + 1` になります。ガイド付きサンプリングには `solver_order=2`、無条件サンプリングには `solver_order=3` の使用を推奨します。

prediction_type (`"epsilon"`, `"sample"`, `"v_prediction"`, or `"flow_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`), `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` かつ `predict_x0=True` の場合にのみ有効です。

predict_x0 (`bool`、デフォルトは`True`) : 予測されたx0に対して更新アルゴリズムを使用するかどうか。

solver_type (`"bh1"` または `"bh2"`、デフォルトは `"bh2"`) : UniPC のソルバータイプ。ステップ数が 10 未満の無条件サンプリングには `bh1` を、それ以外には `bh2` を使用することをお勧めします。

lower_order_final (`bool`、デフォルトは `True`) : 最終ステップで低次数のソルバーを使用するかどうか。15 回の推論ステップ未満の場合にのみ有効です。ステップ数が 15 回未満、特に 10 回以下の場合は、DPMSolver のサンプリングを安定させることができます。

disable_corrector (`list`、デフォルトは `[]`) : `epsilon_theta(x_t, c)` と `epsilon_theta(x_t^c, c)` の間の不一致を緩和するために、どのステップで corrector を無効にするかを決定します。この不一致は、guidance scale が大きい場合に収束に影響を与える可能性があります。通常、corrector は最初の数ステップの間無効にされます。

solver_p (`SchedulerMixin`、デフォルトは `None`) : 指定された場合、アルゴリズムが `solver_p + UniC` になる他のスケジューラ。

use_karras_sigmas (`bool`, *任意*, デフォルトは `False`) : サンプリングプロセス中のノイズスケジュールにおけるステップサイズに Karras シグマを使用するかどうか。`True` の場合、シグマはノイズレベルの列 {σi} に基づいて決定されます。

use_exponential_sigmas (`bool`、*任意*、デフォルトは`False`) : サンプリングプロセス中のノイズスケジュールにおいて、ステップサイズに指数シグマを使用するかどうか。

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`) : サンプリングプロセス中のノイズスケジュールにおいて、ステップサイズにフローシグマを使用するかどうか。

timestep_spacing (`"linspace"`, `"leading"`, or `"trailing"`, 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) : 一部のモデルファミリーで必要とされる、推論ステップに追加されるオフセットです。

final_sigmas_type (`"zero"` または `"sigma_min"`、デフォルトは `"zero"`) : サンプリングプロセス中のノイズスケジュールにおける最終的な `sigma` 値。`"sigma_min"` の場合、最終的な sigma は学習スケジュールの最後の sigma と同じになります。`zero` の場合、最終的な sigma は 0 に設定されます。

rescale_betas_zero_snr (`bool`、デフォルトは`False`) : ベータを再スケーリングして、終端SNRをゼロにするかどうか。これにより、モデルは中間の明るさに限定されず、非常に明るく暗いサンプルを生成できるようになります。[`--offset_noise`](https://github.com/huggingface/diffusers/blob/74fd735eb073eb1d774b1ab4154a0876eb82f055/examples/dreambooth/train_dreambooth.py#L506)とゆるく関連しています。

`UniPCMultistepScheduler` は、拡散モデルの高速サンプリングのために設計された、学習不要のフレームワークです。

このモデルは [SchedulerMixin](/docs/diffusers/v0.43.0/ja/api/schedulers/overview#diffusers.SchedulerMixin) と [ConfigMixin](/docs/diffusers/v0.43.0/ja/api/configuration#diffusers.ConfigMixin) を継承しています。読み込みや保存など、ライブラリがすべてのスケジューラに対して実装している汎用的なメソッドについては、スーパークラスのドキュメントを参照してください。

#### add_noise[[diffusers.UniPCMultistepScheduler.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_unipc_multistep.py#L1250)

**パラメータ:**

original_samples (`torch.Tensor`) : ノイズが加えられていない元のサンプル。

noise (`torch.Tensor`) : サンプルに追加するノイズ。

timesteps (`torch.IntTensor`) : サンプルにノイズを付加するタイムステップ。

**戻り値:** `torch.Tensor`

ノイズ付きサンプル。

指定されたタイムステップにおけるノイズスケジュールに従って、元のサンプルにノイズを追加します。

#### convert_model_output[[diffusers.UniPCMultistepScheduler.convert_model_output]]

```python
convert_model_output(model_output: Tensor, *args, sample: Tensor = None, **kwargs)
```

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/schedulers/scheduling_unipc_multistep.py#L760)

**パラメータ:**

model_output (`torch.Tensor`) : 学習済み拡散モデルからの直接の出力です。

timestep (`int`) : 拡散チェーンにおける現在の離散タイムステップ。

sample (`torch.Tensor`) : 拡散プロセスによって生成されたサンプルの現在のインスタンス。

**戻り値:** `torch.Tensor`

変換後のモデルの出力。

モデルの出力を、UniPCアルゴリズムが要求する対応する型に変換します。

#### index_for_timestep[[diffusers.UniPCMultistepScheduler.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_unipc_multistep.py#L1100)

**パラメータ:**

timestep (`int` または `torch.Tensor`) : インデックスを特定するためのタイムステップ。

schedule_timesteps (`torch.Tensor`, *任意*) : 検索対象のタイムステップスケジュール。`None` の場合は `self.timesteps` を使用します。

**戻り値:** `int`

スケジュールにおけるタイムステップのインデックス。

スケジュール内の指定されたタイムステップのインデックスを取得します。

#### multistep_uni_c_bh_update[[diffusers.UniPCMultistepScheduler.multistep_uni_c_bh_update]]

```python
multistep_uni_c_bh_update(this_model_output: Tensor, *args, last_sample: Tensor = None, this_sample: Tensor = None, order: int = None, **kwargs)
```

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/schedulers/scheduling_unipc_multistep.py#L962)

**パラメータ:**

this_model_output (`torch.Tensor`) : `x_t` におけるモデルの出力。

this_timestep (`int`) : 現在のタイムステップ `t`。

last_sample (`torch.Tensor`) : 最後の予測器 `x_{t-1}` による生成サンプル。

this_sample (`torch.Tensor`) : 最後の予測器 `x_{t}` 以降に生成されたサンプルです。

order (`int`) : このステップにおける UniC-p の `p` です。精度の有効な次数は `order + 1` であるべきです。

**戻り値:** `torch.Tensor`

現在のタイムステップにおける修正済みサンプルテンソル。

UniC（B(h)版）の1ステップ。

#### multistep_uni_p_bh_update[[diffusers.UniPCMultistepScheduler.multistep_uni_p_bh_update]]

```python
multistep_uni_p_bh_update(model_output: Tensor, *args, sample: Tensor = None, order: int = None, **kwargs)
```

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/schedulers/scheduling_unipc_multistep.py#L833)

**パラメータ:**

model_output (`torch.Tensor`) : 現在のタイムステップにおける学習済み拡散モデルの直接出力。

prev_timestep (`int`) : 拡散チェーンにおける直前の離散タイムステップ。

sample (`torch.Tensor`) : 拡散プロセスによって生成されたサンプルの現在のインスタンス。

order (`int`) : このタイムステップにおける UniP の順序（UniPC-p の *p* に相当します）。

**戻り値:** `torch.Tensor`

前のタイムステップのサンプルテンソル。

UniP（B(h)版）の1ステップ。または、指定されている場合は`self.solver_p`が使用されます。

#### scale_model_input[[diffusers.UniPCMultistepScheduler.scale_model_input]]

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

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/schedulers/scheduling_unipc_multistep.py#L1234)

**パラメータ:**

sample (`torch.Tensor`) : 入力サンプル。

**戻り値:** `torch.Tensor`

スケーリングされた入力サンプル。

現在のタイムステップに応じて、デノイジングモデルの入力をスケーリングする必要があるスケジューラとの相互運用性を保証します。

#### set_begin_index[[diffusers.UniPCMultistepScheduler.set_begin_index]]

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

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/schedulers/scheduling_unipc_multistep.py#L308)

**パラメータ:**

begin_index (`int`、デフォルトは`0`) : スケジューラの開始インデックス。

スケジューラの開始インデックスを設定します。この関数は、推論の前にパイプラインから実行する必要があります。

#### set_timesteps[[diffusers.UniPCMultistepScheduler.set_timesteps]]

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

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/schedulers/scheduling_unipc_multistep.py#L318)

**パラメータ:**

num_inference_steps (`int`) : 事前学習済みモデルでサンプルを生成する際に使用される拡散ステップの数。

device (`str` または `torch.device`、*任意*) : timesteps を移動先とするデバイスです。`None` の場合、timesteps は移動されません。

sigmas (`List[float]`, *optional*) : 各拡散ステップで使用されるシグマの自定义値。`None` の場合、シグマは自動的に計算されます。

mu (`float`, *任意*) : 指数型時間シフトタイプを使用する場合の動的シフトにおける任意の mu パラメータ。

拡散チェーンで使用される離散タイムステップを設定します（推論の実行前に実行する必要があります）。

#### ステップ[[diffusers.UniPCMultistepScheduler.step]]

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

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/schedulers/scheduling_unipc_multistep.py#L1153)

**パラメータ:**

model_output (`torch.Tensor`) : 学習済み拡散モデルからの直接の出力です。

timestep (`int` または `torch.Tensor`) : 拡散チェーンにおける現在の離散タイムステップ。

sample (`torch.Tensor`) : 拡散プロセスによって生成されたサンプルの現在のインスタンス。

return_dict (`bool`、デフォルトは`True`) : [SchedulerOutput](/docs/diffusers/v0.43.0/ja/api/schedulers/ipndm#diffusers.schedulers.scheduling_utils.SchedulerOutput)を返すか、`tuple`を返すかを指定します。

**戻り値:** [SchedulerOutput](/docs/diffusers/v0.43.0/ja/api/schedulers/ipndm#diffusers.schedulers.scheduling_utils.SchedulerOutput) または `tuple`

`True` の場合、[SchedulerOutput](/docs/diffusers/v0.43.0/ja/api/schedulers/ipndm#diffusers.schedulers.scheduling_utils.SchedulerOutput) が返され、それ以外の場合は、最初の要素がサンプルテンソルであるタプルが返されます。

前のタイムステップのサンプルをSDEを逆方向に適用することで予測します。この関数は、マルチステップUniPCを用いてサンプルを伝播します。

#### stretch_shift_to_terminal[[diffusers.UniPCMultistepScheduler.stretch_shift_to_terminal]]

```python
stretch_shift_to_terminal(t: Tensor)
```

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/schedulers/scheduling_unipc_multistep.py#L506)

**パラメータ:**

t (`torch.Tensor`) : 伸縮とシフトを行うためのタイムステップのテンソル。

**戻り値:** `torch.Tensor`

最終値が`self.config.shift_terminal`に等しくなるよう調整されたタイムステップのテンソル。

タイムステップスケジュールを伸縮・シフトし、設定された`shift_terminal`設定値で終了することを保証します。

Reference: https://github.com/Lightricks/LTX-Video/blob/a01a171f8fe3d99dce2728d60a73fecf4d4238ae/ltx_video/schedulers/rf.py#L51

#### time_shift[[diffusers.UniPCMultistepScheduler.time_shift]]

```python
time_shift(mu: float, sigma: float, t: Tensor)
```

[ソース](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/schedulers/scheduling_unipc_multistep.py#L484)

**パラメータ:**

mu (`float`) : 時間シフト用の mu パラメータ。

sigma (`float`) : 時間シフト用の sigma パラメータ。

t (`torch.Tensor`) : 入力タイムステップ。

**戻り値:** `torch.Tensor`

時間シフトされたタイムステップ。

シグマに時間シフトを適用します。

## 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 (`torch.Tensor`、画像の場合は `(batch_size, num_channels, height, width)` の形状) : 前のタイムステップの計算済みサンプル `(x_{t-1})`。`prev_sample` は、デノイジングループの次のモデル入力として使用する必要があります。

スケジューラーの`step`関数の出力の基底クラス。

