comdoleger commited on
Commit
fc77ed1
·
verified ·
1 Parent(s): b91ebe1

Upload extensions_built_in/diffusion_models/omnigen2/src/schedulers/scheduling_dpmsolver_multistep.py with huggingface_hub

Browse files
extensions_built_in/diffusion_models/omnigen2/src/schedulers/scheduling_dpmsolver_multistep.py ADDED
@@ -0,0 +1,1052 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 TSAIL Team and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # DISCLAIMER: This file is strongly influenced by https://github.com/LuChengTHU/dpm-solver
16
+
17
+ import math
18
+ from typing import List, Optional, Tuple, Union
19
+
20
+ import numpy as np
21
+ import torch
22
+
23
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
24
+ from diffusers.utils import deprecate, is_scipy_available
25
+ from diffusers.utils.torch_utils import randn_tensor
26
+ from diffusers.schedulers.scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput
27
+
28
+
29
+ if is_scipy_available():
30
+ import scipy.stats
31
+
32
+
33
+ # Copied from diffusers.schedulers.scheduling_ddpm.betas_for_alpha_bar
34
+ def betas_for_alpha_bar(
35
+ num_diffusion_timesteps,
36
+ max_beta=0.999,
37
+ alpha_transform_type="cosine",
38
+ ):
39
+ """
40
+ Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of
41
+ (1-beta) over time from t = [0,1].
42
+
43
+ Contains a function alpha_bar that takes an argument t and transforms it to the cumulative product of (1-beta) up
44
+ to that part of the diffusion process.
45
+
46
+
47
+ Args:
48
+ num_diffusion_timesteps (`int`): the number of betas to produce.
49
+ max_beta (`float`): the maximum beta to use; use values lower than 1 to
50
+ prevent singularities.
51
+ alpha_transform_type (`str`, *optional*, default to `cosine`): the type of noise schedule for alpha_bar.
52
+ Choose from `cosine` or `exp`
53
+
54
+ Returns:
55
+ betas (`np.ndarray`): the betas used by the scheduler to step the model outputs
56
+ """
57
+ if alpha_transform_type == "cosine":
58
+
59
+ def alpha_bar_fn(t):
60
+ return math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2
61
+
62
+ elif alpha_transform_type == "exp":
63
+
64
+ def alpha_bar_fn(t):
65
+ return math.exp(t * -12.0)
66
+
67
+ else:
68
+ raise ValueError(f"Unsupported alpha_transform_type: {alpha_transform_type}")
69
+
70
+ betas = []
71
+ for i in range(num_diffusion_timesteps):
72
+ t1 = i / num_diffusion_timesteps
73
+ t2 = (i + 1) / num_diffusion_timesteps
74
+ betas.append(min(1 - alpha_bar_fn(t2) / alpha_bar_fn(t1), max_beta))
75
+ return torch.tensor(betas, dtype=torch.float32)
76
+
77
+
78
+ # Copied from diffusers.schedulers.scheduling_ddim.rescale_zero_terminal_snr
79
+ def rescale_zero_terminal_snr(betas):
80
+ """
81
+ Rescales betas to have zero terminal SNR Based on https://arxiv.org/pdf/2305.08891.pdf (Algorithm 1)
82
+
83
+
84
+ Args:
85
+ betas (`torch.Tensor`):
86
+ the betas that the scheduler is being initialized with.
87
+
88
+ Returns:
89
+ `torch.Tensor`: rescaled betas with zero terminal SNR
90
+ """
91
+ # Convert betas to alphas_bar_sqrt
92
+ alphas = 1.0 - betas
93
+ alphas_cumprod = torch.cumprod(alphas, dim=0)
94
+ alphas_bar_sqrt = alphas_cumprod.sqrt()
95
+
96
+ # Store old values.
97
+ alphas_bar_sqrt_0 = alphas_bar_sqrt[0].clone()
98
+ alphas_bar_sqrt_T = alphas_bar_sqrt[-1].clone()
99
+
100
+ # Shift so the last timestep is zero.
101
+ alphas_bar_sqrt -= alphas_bar_sqrt_T
102
+
103
+ # Scale so the first timestep is back to the old value.
104
+ alphas_bar_sqrt *= alphas_bar_sqrt_0 / (alphas_bar_sqrt_0 - alphas_bar_sqrt_T)
105
+
106
+ # Convert alphas_bar_sqrt to betas
107
+ alphas_bar = alphas_bar_sqrt**2 # Revert sqrt
108
+ alphas = alphas_bar[1:] / alphas_bar[:-1] # Revert cumprod
109
+ alphas = torch.cat([alphas_bar[0:1], alphas])
110
+ betas = 1 - alphas
111
+
112
+ return betas
113
+
114
+
115
+ class DPMSolverMultistepScheduler(SchedulerMixin, ConfigMixin):
116
+ """
117
+ `DPMSolverMultistepScheduler` is a fast dedicated high-order solver for diffusion ODEs.
118
+
119
+ This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
120
+ methods the library implements for all schedulers such as loading and saving.
121
+
122
+ Args:
123
+ num_train_timesteps (`int`, defaults to 1000):
124
+ The number of diffusion steps to train the model.
125
+ beta_start (`float`, defaults to 0.0001):
126
+ The starting `beta` value of inference.
127
+ beta_end (`float`, defaults to 0.02):
128
+ The final `beta` value.
129
+ beta_schedule (`str`, defaults to `"linear"`):
130
+ The beta schedule, a mapping from a beta range to a sequence of betas for stepping the model. Choose from
131
+ `linear`, `scaled_linear`, or `squaredcos_cap_v2`.
132
+ trained_betas (`np.ndarray`, *optional*):
133
+ Pass an array of betas directly to the constructor to bypass `beta_start` and `beta_end`.
134
+ solver_order (`int`, defaults to 2):
135
+ The DPMSolver order which can be `1` or `2` or `3`. It is recommended to use `solver_order=2` for guided
136
+ sampling, and `solver_order=3` for unconditional sampling.
137
+ prediction_type (`str`, defaults to `epsilon`, *optional*):
138
+ Prediction type of the scheduler function; can be `epsilon` (predicts the noise of the diffusion process),
139
+ `sample` (directly predicts the noisy sample), `v_prediction` (see section 2.4 of [Imagen
140
+ Video](https://imagen.research.google/video/paper.pdf) paper), or `flow_prediction`.
141
+ thresholding (`bool`, defaults to `False`):
142
+ Whether to use the "dynamic thresholding" method. This is unsuitable for latent-space diffusion models such
143
+ as Stable Diffusion.
144
+ dynamic_thresholding_ratio (`float`, defaults to 0.995):
145
+ The ratio for the dynamic thresholding method. Valid only when `thresholding=True`.
146
+ sample_max_value (`float`, defaults to 1.0):
147
+ The threshold value for dynamic thresholding. Valid only when `thresholding=True` and
148
+ `algorithm_type="dpmsolver++"`.
149
+ algorithm_type (`str`, defaults to `dpmsolver++`):
150
+ Algorithm type for the solver; can be `dpmsolver`, `dpmsolver++`, `sde-dpmsolver` or `sde-dpmsolver++`. The
151
+ `dpmsolver` type implements the algorithms in the [DPMSolver](https://huggingface.co/papers/2206.00927)
152
+ paper, and the `dpmsolver++` type implements the algorithms in the
153
+ [DPMSolver++](https://huggingface.co/papers/2211.01095) paper. It is recommended to use `dpmsolver++` or
154
+ `sde-dpmsolver++` with `solver_order=2` for guided sampling like in Stable Diffusion.
155
+ solver_type (`str`, defaults to `midpoint`):
156
+ Solver type for the second-order solver; can be `midpoint` or `heun`. The solver type slightly affects the
157
+ sample quality, especially for a small number of steps. It is recommended to use `midpoint` solvers.
158
+ lower_order_final (`bool`, defaults to `True`):
159
+ Whether to use lower-order solvers in the final steps. Only valid for < 15 inference steps. This can
160
+ stabilize the sampling of DPMSolver for steps < 15, especially for steps <= 10.
161
+ euler_at_final (`bool`, defaults to `False`):
162
+ Whether to use Euler's method in the final step. It is a trade-off between numerical stability and detail
163
+ richness. This can stabilize the sampling of the SDE variant of DPMSolver for small number of inference
164
+ steps, but sometimes may result in blurring.
165
+ use_karras_sigmas (`bool`, *optional*, defaults to `False`):
166
+ Whether to use Karras sigmas for step sizes in the noise schedule during the sampling process. If `True`,
167
+ the sigmas are determined according to a sequence of noise levels {σi}.
168
+ use_exponential_sigmas (`bool`, *optional*, defaults to `False`):
169
+ Whether to use exponential sigmas for step sizes in the noise schedule during the sampling process.
170
+ use_beta_sigmas (`bool`, *optional*, defaults to `False`):
171
+ Whether to use beta sigmas for step sizes in the noise schedule during the sampling process. Refer to [Beta
172
+ Sampling is All You Need](https://huggingface.co/papers/2407.12173) for more information.
173
+ use_lu_lambdas (`bool`, *optional*, defaults to `False`):
174
+ Whether to use the uniform-logSNR for step sizes proposed by Lu's DPM-Solver in the noise schedule during
175
+ the sampling process. If `True`, the sigmas and time steps are determined according to a sequence of
176
+ `lambda(t)`.
177
+ use_flow_sigmas (`bool`, *optional*, defaults to `False`):
178
+ Whether to use flow sigmas for step sizes in the noise schedule during the sampling process.
179
+ flow_shift (`float`, *optional*, defaults to 1.0):
180
+ The shift value for the timestep schedule for flow matching.
181
+ final_sigmas_type (`str`, defaults to `"zero"`):
182
+ The final `sigma` value for the noise schedule during the sampling process. If `"sigma_min"`, the final
183
+ sigma is the same as the last sigma in the training schedule. If `zero`, the final sigma is set to 0.
184
+ lambda_min_clipped (`float`, defaults to `-inf`):
185
+ Clipping threshold for the minimum value of `lambda(t)` for numerical stability. This is critical for the
186
+ cosine (`squaredcos_cap_v2`) noise schedule.
187
+ variance_type (`str`, *optional*):
188
+ Set to "learned" or "learned_range" for diffusion models that predict variance. If set, the model's output
189
+ contains the predicted Gaussian variance.
190
+ timestep_spacing (`str`, defaults to `"linspace"`):
191
+ The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and
192
+ Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information.
193
+ steps_offset (`int`, defaults to 0):
194
+ An offset added to the inference steps, as required by some model families.
195
+ rescale_betas_zero_snr (`bool`, defaults to `False`):
196
+ Whether to rescale the betas to have zero terminal SNR. This enables the model to generate very bright and
197
+ dark samples instead of limiting it to samples with medium brightness. Loosely related to
198
+ [`--offset_noise`](https://github.com/huggingface/diffusers/blob/74fd735eb073eb1d774b1ab4154a0876eb82f055/examples/dreambooth/train_dreambooth.py#L506).
199
+ """
200
+
201
+ _compatibles = [e.name for e in KarrasDiffusionSchedulers]
202
+ order = 1
203
+
204
+ @register_to_config
205
+ def __init__(
206
+ self,
207
+ num_train_timesteps: int = 1000,
208
+ beta_start: float = 0.0001,
209
+ beta_end: float = 0.02,
210
+ beta_schedule: str = "linear",
211
+ trained_betas: Optional[Union[np.ndarray, List[float]]] = None,
212
+ solver_order: int = 2,
213
+ prediction_type: str = "epsilon",
214
+ thresholding: bool = False,
215
+ dynamic_thresholding_ratio: float = 0.995,
216
+ sample_max_value: float = 1.0,
217
+ algorithm_type: str = "dpmsolver++",
218
+ solver_type: str = "midpoint",
219
+ lower_order_final: bool = True,
220
+ euler_at_final: bool = False,
221
+ final_sigmas_type: str = 'zero',
222
+ dynamic_time_shift: bool = True
223
+ ):
224
+ if algorithm_type in ["dpmsolver", "sde-dpmsolver"]:
225
+ deprecation_message = f"algorithm_type {algorithm_type} is deprecated and will be removed in a future version. Choose from `dpmsolver++` or `sde-dpmsolver++` instead"
226
+ deprecate("algorithm_types dpmsolver and sde-dpmsolver", "1.0.0", deprecation_message)
227
+
228
+ if trained_betas is not None:
229
+ self.betas = torch.tensor(trained_betas, dtype=torch.float32)
230
+ elif beta_schedule == "linear":
231
+ self.betas = torch.linspace(beta_start, beta_end, num_train_timesteps, dtype=torch.float32)
232
+ elif beta_schedule == "scaled_linear":
233
+ # this schedule is very specific to the latent diffusion model.
234
+ self.betas = torch.linspace(beta_start**0.5, beta_end**0.5, num_train_timesteps, dtype=torch.float32) ** 2
235
+ elif beta_schedule == "squaredcos_cap_v2":
236
+ # Glide cosine schedule
237
+ self.betas = betas_for_alpha_bar(num_train_timesteps)
238
+ else:
239
+ raise NotImplementedError(f"{beta_schedule} is not implemented for {self.__class__}")
240
+ self.alphas = 1.0 - self.betas
241
+ self.alphas_cumprod = torch.cumprod(self.alphas, dim=0)
242
+
243
+ # Currently we only support VP-type noise schedule
244
+ self.alpha_t = torch.sqrt(self.alphas_cumprod)
245
+ self.sigma_t = torch.sqrt(1 - self.alphas_cumprod)
246
+ self.lambda_t = torch.log(self.alpha_t) - torch.log(self.sigma_t)
247
+ self.sigmas = ((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5
248
+
249
+ # standard deviation of the initial noise distribution
250
+ self.init_noise_sigma = 1.0
251
+
252
+ # settings for DPM-Solver
253
+ if algorithm_type not in ["dpmsolver", "dpmsolver++", "sde-dpmsolver", "sde-dpmsolver++"]:
254
+ if algorithm_type == "deis":
255
+ self.register_to_config(algorithm_type="dpmsolver++")
256
+ else:
257
+ raise NotImplementedError(f"{algorithm_type} is not implemented for {self.__class__}")
258
+
259
+ if solver_type not in ["midpoint", "heun"]:
260
+ if solver_type in ["logrho", "bh1", "bh2"]:
261
+ self.register_to_config(solver_type="midpoint")
262
+ else:
263
+ raise NotImplementedError(f"{solver_type} is not implemented for {self.__class__}")
264
+
265
+ # if algorithm_type not in ["dpmsolver++", "sde-dpmsolver++"] and final_sigmas_type == "zero":
266
+ # raise ValueError(
267
+ # f"`final_sigmas_type` {final_sigmas_type} is not supported for `algorithm_type` {algorithm_type}. Please choose `sigma_min` instead."
268
+ # )
269
+
270
+ # setable values
271
+ self.num_inference_steps = None
272
+ timesteps = np.linspace(0, num_train_timesteps - 1, num_train_timesteps, dtype=np.float32)[::-1].copy()
273
+ self.timesteps = torch.from_numpy(timesteps)
274
+ self.model_outputs = [None] * solver_order
275
+ self.lower_order_nums = 0
276
+ self._step_index = None
277
+ self._begin_index = None
278
+ self.sigmas = self.sigmas.to("cpu") # to avoid too much CPU/GPU communication
279
+
280
+ @property
281
+ def step_index(self):
282
+ """
283
+ The index counter for current timestep. It will increase 1 after each scheduler step.
284
+ """
285
+ return self._step_index
286
+
287
+ @property
288
+ def begin_index(self):
289
+ """
290
+ The index for the first timestep. It should be set from pipeline with `set_begin_index` method.
291
+ """
292
+ return self._begin_index
293
+
294
+ def set_begin_index(self, begin_index: int = 0):
295
+ """
296
+ Sets the begin index for the scheduler. This function should be run from pipeline before the inference.
297
+
298
+ Args:
299
+ begin_index (`int`):
300
+ The begin index for the scheduler.
301
+ """
302
+ self._begin_index = begin_index
303
+
304
+ def set_timesteps(
305
+ self,
306
+ num_inference_steps: int = None,
307
+ device: Union[str, torch.device] = None,
308
+ timesteps: Optional[List[int]] = None,
309
+ num_tokens: Optional[int] = None
310
+ ):
311
+ if timesteps is None:
312
+ self.num_inference_steps = num_inference_steps
313
+ timesteps = np.linspace(0, 1, num_inference_steps + 1, dtype=np.float32)[:-1]
314
+ if self.config.dynamic_time_shift and num_tokens is not None:
315
+ m = np.sqrt(num_tokens) / 40 # when input resolution is 320 * 320, m = 1, when input resolution is 1024 * 1024, m = 3.2
316
+ timesteps = timesteps / (m - m * timesteps + timesteps)
317
+
318
+ timesteps = torch.from_numpy(timesteps).to(dtype=torch.float32, device=device)
319
+ sigmas = torch.cat([1 - timesteps, torch.zeros(1, device=timesteps.device)])
320
+
321
+ self.sigmas = sigmas
322
+ self.timesteps = timesteps
323
+
324
+ self.num_inference_steps = len(timesteps)
325
+
326
+ self.model_outputs = [
327
+ None,
328
+ ] * self.config.solver_order
329
+ self.lower_order_nums = 0
330
+
331
+ # add an index counter for schedulers that allow duplicated timesteps
332
+ self._step_index = None
333
+ self._begin_index = None
334
+ self.sigmas = self.sigmas.to("cpu") # to avoid too much CPU/GPU communication
335
+
336
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler._threshold_sample
337
+ def _threshold_sample(self, sample: torch.Tensor) -> torch.Tensor:
338
+ """
339
+ "Dynamic thresholding: At each sampling step we set s to a certain percentile absolute pixel value in xt0 (the
340
+ prediction of x_0 at timestep t), and if s > 1, then we threshold xt0 to the range [-s, s] and then divide by
341
+ s. Dynamic thresholding pushes saturated pixels (those near -1 and 1) inwards, thereby actively preventing
342
+ pixels from saturation at each step. We find that dynamic thresholding results in significantly better
343
+ photorealism as well as better image-text alignment, especially when using very large guidance weights."
344
+
345
+ https://arxiv.org/abs/2205.11487
346
+ """
347
+ dtype = sample.dtype
348
+ batch_size, channels, *remaining_dims = sample.shape
349
+
350
+ if dtype not in (torch.float32, torch.float64):
351
+ sample = sample.float() # upcast for quantile calculation, and clamp not implemented for cpu half
352
+
353
+ # Flatten sample for doing quantile calculation along each image
354
+ sample = sample.reshape(batch_size, channels * np.prod(remaining_dims))
355
+
356
+ abs_sample = sample.abs() # "a certain percentile absolute pixel value"
357
+
358
+ s = torch.quantile(abs_sample, self.config.dynamic_thresholding_ratio, dim=1)
359
+ s = torch.clamp(
360
+ s, min=1, max=self.config.sample_max_value
361
+ ) # When clamped to min=1, equivalent to standard clipping to [-1, 1]
362
+ s = s.unsqueeze(1) # (batch_size, 1) because clamp will broadcast along dim=0
363
+ sample = torch.clamp(sample, -s, s) / s # "we threshold xt0 to the range [-s, s] and then divide by s"
364
+
365
+ sample = sample.reshape(batch_size, channels, *remaining_dims)
366
+ sample = sample.to(dtype)
367
+
368
+ return sample
369
+
370
+ # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._sigma_to_t
371
+ def _sigma_to_t(self, sigma, log_sigmas):
372
+ # get log sigma
373
+ log_sigma = np.log(np.maximum(sigma, 1e-10))
374
+
375
+ # get distribution
376
+ dists = log_sigma - log_sigmas[:, np.newaxis]
377
+
378
+ # get sigmas range
379
+ low_idx = np.cumsum((dists >= 0), axis=0).argmax(axis=0).clip(max=log_sigmas.shape[0] - 2)
380
+ high_idx = low_idx + 1
381
+
382
+ low = log_sigmas[low_idx]
383
+ high = log_sigmas[high_idx]
384
+
385
+ # interpolate sigmas
386
+ w = (low - log_sigma) / (low - high)
387
+ w = np.clip(w, 0, 1)
388
+
389
+ # transform interpolation to time range
390
+ t = (1 - w) * low_idx + w * high_idx
391
+ t = t.reshape(sigma.shape)
392
+ return t
393
+
394
+ def _sigma_to_alpha_sigma_t(self, sigma):
395
+ alpha_t = 1 - sigma
396
+ sigma_t = sigma
397
+
398
+ return alpha_t, sigma_t
399
+
400
+ # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._convert_to_karras
401
+ def _convert_to_karras(self, in_sigmas: torch.Tensor, num_inference_steps) -> torch.Tensor:
402
+ """Constructs the noise schedule of Karras et al. (2022)."""
403
+
404
+ # Hack to make sure that other schedulers which copy this function don't break
405
+ # TODO: Add this logic to the other schedulers
406
+ if hasattr(self.config, "sigma_min"):
407
+ sigma_min = self.config.sigma_min
408
+ else:
409
+ sigma_min = None
410
+
411
+ if hasattr(self.config, "sigma_max"):
412
+ sigma_max = self.config.sigma_max
413
+ else:
414
+ sigma_max = None
415
+
416
+ sigma_min = sigma_min if sigma_min is not None else in_sigmas[-1].item()
417
+ sigma_max = sigma_max if sigma_max is not None else in_sigmas[0].item()
418
+
419
+ rho = 7.0 # 7.0 is the value used in the paper
420
+ ramp = np.linspace(0, 1, num_inference_steps)
421
+ min_inv_rho = sigma_min ** (1 / rho)
422
+ max_inv_rho = sigma_max ** (1 / rho)
423
+ sigmas = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
424
+ return sigmas
425
+
426
+ def _convert_to_lu(self, in_lambdas: torch.Tensor, num_inference_steps) -> torch.Tensor:
427
+ """Constructs the noise schedule of Lu et al. (2022)."""
428
+
429
+ lambda_min: float = in_lambdas[-1].item()
430
+ lambda_max: float = in_lambdas[0].item()
431
+
432
+ rho = 1.0 # 1.0 is the value used in the paper
433
+ ramp = np.linspace(0, 1, num_inference_steps)
434
+ min_inv_rho = lambda_min ** (1 / rho)
435
+ max_inv_rho = lambda_max ** (1 / rho)
436
+ lambdas = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
437
+ return lambdas
438
+
439
+ # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._convert_to_exponential
440
+ def _convert_to_exponential(self, in_sigmas: torch.Tensor, num_inference_steps: int) -> torch.Tensor:
441
+ """Constructs an exponential noise schedule."""
442
+
443
+ # Hack to make sure that other schedulers which copy this function don't break
444
+ # TODO: Add this logic to the other schedulers
445
+ if hasattr(self.config, "sigma_min"):
446
+ sigma_min = self.config.sigma_min
447
+ else:
448
+ sigma_min = None
449
+
450
+ if hasattr(self.config, "sigma_max"):
451
+ sigma_max = self.config.sigma_max
452
+ else:
453
+ sigma_max = None
454
+
455
+ sigma_min = sigma_min if sigma_min is not None else in_sigmas[-1].item()
456
+ sigma_max = sigma_max if sigma_max is not None else in_sigmas[0].item()
457
+
458
+ sigmas = np.exp(np.linspace(math.log(sigma_max), math.log(sigma_min), num_inference_steps))
459
+ return sigmas
460
+
461
+ # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._convert_to_beta
462
+ def _convert_to_beta(
463
+ self, in_sigmas: torch.Tensor, num_inference_steps: int, alpha: float = 0.6, beta: float = 0.6
464
+ ) -> torch.Tensor:
465
+ """From "Beta Sampling is All You Need" [arXiv:2407.12173] (Lee et. al, 2024)"""
466
+
467
+ # Hack to make sure that other schedulers which copy this function don't break
468
+ # TODO: Add this logic to the other schedulers
469
+ if hasattr(self.config, "sigma_min"):
470
+ sigma_min = self.config.sigma_min
471
+ else:
472
+ sigma_min = None
473
+
474
+ if hasattr(self.config, "sigma_max"):
475
+ sigma_max = self.config.sigma_max
476
+ else:
477
+ sigma_max = None
478
+
479
+ sigma_min = sigma_min if sigma_min is not None else in_sigmas[-1].item()
480
+ sigma_max = sigma_max if sigma_max is not None else in_sigmas[0].item()
481
+
482
+ sigmas = np.array(
483
+ [
484
+ sigma_min + (ppf * (sigma_max - sigma_min))
485
+ for ppf in [
486
+ scipy.stats.beta.ppf(timestep, alpha, beta)
487
+ for timestep in 1 - np.linspace(0, 1, num_inference_steps)
488
+ ]
489
+ ]
490
+ )
491
+ return sigmas
492
+
493
+ def convert_model_output(
494
+ self,
495
+ model_output: torch.Tensor,
496
+ *args,
497
+ sample: torch.Tensor = None,
498
+ **kwargs,
499
+ ) -> torch.Tensor:
500
+ """
501
+ Convert the model output to the corresponding type the DPMSolver/DPMSolver++ algorithm needs. DPM-Solver is
502
+ designed to discretize an integral of the noise prediction model, and DPM-Solver++ is designed to discretize an
503
+ integral of the data prediction model.
504
+
505
+ <Tip>
506
+
507
+ The algorithm and model type are decoupled. You can use either DPMSolver or DPMSolver++ for both noise
508
+ prediction and data prediction models.
509
+
510
+ </Tip>
511
+
512
+ Args:
513
+ model_output (`torch.Tensor`):
514
+ The direct output from the learned diffusion model.
515
+ sample (`torch.Tensor`):
516
+ A current instance of a sample created by the diffusion process.
517
+
518
+ Returns:
519
+ `torch.Tensor`:
520
+ The converted model output.
521
+ """
522
+ timestep = args[0] if len(args) > 0 else kwargs.pop("timestep", None)
523
+ if sample is None:
524
+ if len(args) > 1:
525
+ sample = args[1]
526
+ else:
527
+ raise ValueError("missing `sample` as a required keyward argument")
528
+ if timestep is not None:
529
+ deprecate(
530
+ "timesteps",
531
+ "1.0.0",
532
+ "Passing `timesteps` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
533
+ )
534
+
535
+ # DPM-Solver++ needs to solve an integral of the data prediction model.
536
+ if self.config.algorithm_type in ["dpmsolver++", "sde-dpmsolver++"]:
537
+ if self.config.prediction_type == "epsilon":
538
+ # DPM-Solver and DPM-Solver++ only need the "mean" output.
539
+ if self.config.variance_type in ["learned", "learned_range"]:
540
+ model_output = model_output[:, :3]
541
+ sigma = self.sigmas[self.step_index]
542
+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma)
543
+ x0_pred = (sample - sigma_t * model_output) / alpha_t
544
+ elif self.config.prediction_type == "sample":
545
+ x0_pred = model_output
546
+ elif self.config.prediction_type == "v_prediction":
547
+ sigma = self.sigmas[self.step_index]
548
+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma)
549
+ x0_pred = alpha_t * sample - sigma_t * model_output
550
+ elif self.config.prediction_type == "flow_prediction":
551
+ sigma_t = self.sigmas[self.step_index]
552
+ x0_pred = sample + sigma_t * model_output
553
+ else:
554
+ raise ValueError(
555
+ f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, "
556
+ "`v_prediction`, or `flow_prediction` for the DPMSolverMultistepScheduler."
557
+ )
558
+
559
+ if self.config.thresholding:
560
+ x0_pred = self._threshold_sample(x0_pred)
561
+
562
+ return x0_pred
563
+
564
+ # DPM-Solver needs to solve an integral of the noise prediction model.
565
+ elif self.config.algorithm_type in ["dpmsolver", "sde-dpmsolver"]:
566
+ if self.config.prediction_type == "epsilon":
567
+ # DPM-Solver and DPM-Solver++ only need the "mean" output.
568
+ if self.config.variance_type in ["learned", "learned_range"]:
569
+ epsilon = model_output[:, :3]
570
+ else:
571
+ epsilon = model_output
572
+ elif self.config.prediction_type == "sample":
573
+ sigma = self.sigmas[self.step_index]
574
+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma)
575
+ epsilon = (sample - alpha_t * model_output) / sigma_t
576
+ elif self.config.prediction_type == "v_prediction":
577
+ sigma = self.sigmas[self.step_index]
578
+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma)
579
+ epsilon = alpha_t * model_output + sigma_t * sample
580
+ else:
581
+ raise ValueError(
582
+ f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or"
583
+ " `v_prediction` for the DPMSolverMultistepScheduler."
584
+ )
585
+
586
+ if self.config.thresholding:
587
+ sigma = self.sigmas[self.step_index]
588
+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma)
589
+ x0_pred = (sample - sigma_t * epsilon) / alpha_t
590
+ x0_pred = self._threshold_sample(x0_pred)
591
+ epsilon = (sample - alpha_t * x0_pred) / sigma_t
592
+
593
+ return epsilon
594
+
595
+ def dpm_solver_first_order_update(
596
+ self,
597
+ model_output: torch.Tensor,
598
+ *args,
599
+ sample: torch.Tensor = None,
600
+ noise: Optional[torch.Tensor] = None,
601
+ **kwargs,
602
+ ) -> torch.Tensor:
603
+ """
604
+ One step for the first-order DPMSolver (equivalent to DDIM).
605
+
606
+ Args:
607
+ model_output (`torch.Tensor`):
608
+ The direct output from the learned diffusion model.
609
+ sample (`torch.Tensor`):
610
+ A current instance of a sample created by the diffusion process.
611
+
612
+ Returns:
613
+ `torch.Tensor`:
614
+ The sample tensor at the previous timestep.
615
+ """
616
+ timestep = args[0] if len(args) > 0 else kwargs.pop("timestep", None)
617
+ prev_timestep = args[1] if len(args) > 1 else kwargs.pop("prev_timestep", None)
618
+ if sample is None:
619
+ if len(args) > 2:
620
+ sample = args[2]
621
+ else:
622
+ raise ValueError(" missing `sample` as a required keyward argument")
623
+ if timestep is not None:
624
+ deprecate(
625
+ "timesteps",
626
+ "1.0.0",
627
+ "Passing `timesteps` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
628
+ )
629
+
630
+ if prev_timestep is not None:
631
+ deprecate(
632
+ "prev_timestep",
633
+ "1.0.0",
634
+ "Passing `prev_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
635
+ )
636
+
637
+ sigma_t, sigma_s = self.sigmas[self.step_index + 1], self.sigmas[self.step_index]
638
+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t)
639
+ alpha_s, sigma_s = self._sigma_to_alpha_sigma_t(sigma_s)
640
+ lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
641
+ lambda_s = torch.log(alpha_s) - torch.log(sigma_s)
642
+
643
+ h = lambda_t - lambda_s
644
+ if self.config.algorithm_type == "dpmsolver++":
645
+ x_t = (sigma_t / sigma_s) * sample - (alpha_t * (torch.exp(-h) - 1.0)) * model_output
646
+ elif self.config.algorithm_type == "dpmsolver":
647
+ x_t = (alpha_t / alpha_s) * sample - (sigma_t * (torch.exp(h) - 1.0)) * model_output
648
+ elif self.config.algorithm_type == "sde-dpmsolver++":
649
+ assert noise is not None
650
+ x_t = (
651
+ (sigma_t / sigma_s * torch.exp(-h)) * sample
652
+ + (alpha_t * (1 - torch.exp(-2.0 * h))) * model_output
653
+ + sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise
654
+ )
655
+ elif self.config.algorithm_type == "sde-dpmsolver":
656
+ assert noise is not None
657
+ x_t = (
658
+ (alpha_t / alpha_s) * sample
659
+ - 2.0 * (sigma_t * (torch.exp(h) - 1.0)) * model_output
660
+ + sigma_t * torch.sqrt(torch.exp(2 * h) - 1.0) * noise
661
+ )
662
+ return x_t
663
+
664
+ def multistep_dpm_solver_second_order_update(
665
+ self,
666
+ model_output_list: List[torch.Tensor],
667
+ *args,
668
+ sample: torch.Tensor = None,
669
+ noise: Optional[torch.Tensor] = None,
670
+ **kwargs,
671
+ ) -> torch.Tensor:
672
+ """
673
+ One step for the second-order multistep DPMSolver.
674
+
675
+ Args:
676
+ model_output_list (`List[torch.Tensor]`):
677
+ The direct outputs from learned diffusion model at current and latter timesteps.
678
+ sample (`torch.Tensor`):
679
+ A current instance of a sample created by the diffusion process.
680
+
681
+ Returns:
682
+ `torch.Tensor`:
683
+ The sample tensor at the previous timestep.
684
+ """
685
+ timestep_list = args[0] if len(args) > 0 else kwargs.pop("timestep_list", None)
686
+ prev_timestep = args[1] if len(args) > 1 else kwargs.pop("prev_timestep", None)
687
+ if sample is None:
688
+ if len(args) > 2:
689
+ sample = args[2]
690
+ else:
691
+ raise ValueError(" missing `sample` as a required keyward argument")
692
+ if timestep_list is not None:
693
+ deprecate(
694
+ "timestep_list",
695
+ "1.0.0",
696
+ "Passing `timestep_list` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
697
+ )
698
+
699
+ if prev_timestep is not None:
700
+ deprecate(
701
+ "prev_timestep",
702
+ "1.0.0",
703
+ "Passing `prev_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
704
+ )
705
+
706
+ sigma_t, sigma_s0, sigma_s1 = (
707
+ self.sigmas[self.step_index + 1],
708
+ self.sigmas[self.step_index],
709
+ self.sigmas[self.step_index - 1],
710
+ )
711
+
712
+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t)
713
+ alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0)
714
+ alpha_s1, sigma_s1 = self._sigma_to_alpha_sigma_t(sigma_s1)
715
+
716
+ lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
717
+ lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0)
718
+ lambda_s1 = torch.log(alpha_s1) - torch.log(sigma_s1)
719
+
720
+ m0, m1 = model_output_list[-1], model_output_list[-2]
721
+
722
+ h, h_0 = lambda_t - lambda_s0, lambda_s0 - lambda_s1
723
+ r0 = h_0 / h
724
+ D0, D1 = m0, (1.0 / r0) * (m0 - m1)
725
+ if self.config.algorithm_type == "dpmsolver++":
726
+ # See https://arxiv.org/abs/2211.01095 for detailed derivations
727
+ if self.config.solver_type == "midpoint":
728
+ x_t = (
729
+ (sigma_t / sigma_s0) * sample
730
+ - (alpha_t * (torch.exp(-h) - 1.0)) * D0
731
+ - 0.5 * (alpha_t * (torch.exp(-h) - 1.0)) * D1
732
+ )
733
+ elif self.config.solver_type == "heun":
734
+ x_t = (
735
+ (sigma_t / sigma_s0) * sample
736
+ - (alpha_t * (torch.exp(-h) - 1.0)) * D0
737
+ + (alpha_t * ((torch.exp(-h) - 1.0) / h + 1.0)) * D1
738
+ )
739
+ elif self.config.algorithm_type == "dpmsolver":
740
+ # See https://arxiv.org/abs/2206.00927 for detailed derivations
741
+ if self.config.solver_type == "midpoint":
742
+ x_t = (
743
+ (alpha_t / alpha_s0) * sample
744
+ - (sigma_t * (torch.exp(h) - 1.0)) * D0
745
+ - 0.5 * (sigma_t * (torch.exp(h) - 1.0)) * D1
746
+ )
747
+ elif self.config.solver_type == "heun":
748
+ x_t = (
749
+ (alpha_t / alpha_s0) * sample
750
+ - (sigma_t * (torch.exp(h) - 1.0)) * D0
751
+ - (sigma_t * ((torch.exp(h) - 1.0) / h - 1.0)) * D1
752
+ )
753
+ elif self.config.algorithm_type == "sde-dpmsolver++":
754
+ assert noise is not None
755
+ if self.config.solver_type == "midpoint":
756
+ x_t = (
757
+ (sigma_t / sigma_s0 * torch.exp(-h)) * sample
758
+ + (alpha_t * (1 - torch.exp(-2.0 * h))) * D0
759
+ + 0.5 * (alpha_t * (1 - torch.exp(-2.0 * h))) * D1
760
+ + sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise
761
+ )
762
+ elif self.config.solver_type == "heun":
763
+ x_t = (
764
+ (sigma_t / sigma_s0 * torch.exp(-h)) * sample
765
+ + (alpha_t * (1 - torch.exp(-2.0 * h))) * D0
766
+ + (alpha_t * ((1.0 - torch.exp(-2.0 * h)) / (-2.0 * h) + 1.0)) * D1
767
+ + sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise
768
+ )
769
+ elif self.config.algorithm_type == "sde-dpmsolver":
770
+ assert noise is not None
771
+ if self.config.solver_type == "midpoint":
772
+ x_t = (
773
+ (alpha_t / alpha_s0) * sample
774
+ - 2.0 * (sigma_t * (torch.exp(h) - 1.0)) * D0
775
+ - (sigma_t * (torch.exp(h) - 1.0)) * D1
776
+ + sigma_t * torch.sqrt(torch.exp(2 * h) - 1.0) * noise
777
+ )
778
+ elif self.config.solver_type == "heun":
779
+ x_t = (
780
+ (alpha_t / alpha_s0) * sample
781
+ - 2.0 * (sigma_t * (torch.exp(h) - 1.0)) * D0
782
+ - 2.0 * (sigma_t * ((torch.exp(h) - 1.0) / h - 1.0)) * D1
783
+ + sigma_t * torch.sqrt(torch.exp(2 * h) - 1.0) * noise
784
+ )
785
+ return x_t
786
+
787
+ def multistep_dpm_solver_third_order_update(
788
+ self,
789
+ model_output_list: List[torch.Tensor],
790
+ *args,
791
+ sample: torch.Tensor = None,
792
+ noise: Optional[torch.Tensor] = None,
793
+ **kwargs,
794
+ ) -> torch.Tensor:
795
+ """
796
+ One step for the third-order multistep DPMSolver.
797
+
798
+ Args:
799
+ model_output_list (`List[torch.Tensor]`):
800
+ The direct outputs from learned diffusion model at current and latter timesteps.
801
+ sample (`torch.Tensor`):
802
+ A current instance of a sample created by diffusion process.
803
+
804
+ Returns:
805
+ `torch.Tensor`:
806
+ The sample tensor at the previous timestep.
807
+ """
808
+
809
+ timestep_list = args[0] if len(args) > 0 else kwargs.pop("timestep_list", None)
810
+ prev_timestep = args[1] if len(args) > 1 else kwargs.pop("prev_timestep", None)
811
+ if sample is None:
812
+ if len(args) > 2:
813
+ sample = args[2]
814
+ else:
815
+ raise ValueError(" missing`sample` as a required keyward argument")
816
+ if timestep_list is not None:
817
+ deprecate(
818
+ "timestep_list",
819
+ "1.0.0",
820
+ "Passing `timestep_list` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
821
+ )
822
+
823
+ if prev_timestep is not None:
824
+ deprecate(
825
+ "prev_timestep",
826
+ "1.0.0",
827
+ "Passing `prev_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
828
+ )
829
+
830
+ sigma_t, sigma_s0, sigma_s1, sigma_s2 = (
831
+ self.sigmas[self.step_index + 1],
832
+ self.sigmas[self.step_index],
833
+ self.sigmas[self.step_index - 1],
834
+ self.sigmas[self.step_index - 2],
835
+ )
836
+
837
+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t)
838
+ alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0)
839
+ alpha_s1, sigma_s1 = self._sigma_to_alpha_sigma_t(sigma_s1)
840
+ alpha_s2, sigma_s2 = self._sigma_to_alpha_sigma_t(sigma_s2)
841
+
842
+ lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
843
+ lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0)
844
+ lambda_s1 = torch.log(alpha_s1) - torch.log(sigma_s1)
845
+ lambda_s2 = torch.log(alpha_s2) - torch.log(sigma_s2)
846
+
847
+ m0, m1, m2 = model_output_list[-1], model_output_list[-2], model_output_list[-3]
848
+
849
+ h, h_0, h_1 = lambda_t - lambda_s0, lambda_s0 - lambda_s1, lambda_s1 - lambda_s2
850
+ r0, r1 = h_0 / h, h_1 / h
851
+ D0 = m0
852
+ D1_0, D1_1 = (1.0 / r0) * (m0 - m1), (1.0 / r1) * (m1 - m2)
853
+ D1 = D1_0 + (r0 / (r0 + r1)) * (D1_0 - D1_1)
854
+ D2 = (1.0 / (r0 + r1)) * (D1_0 - D1_1)
855
+ if self.config.algorithm_type == "dpmsolver++":
856
+ # See https://arxiv.org/abs/2206.00927 for detailed derivations
857
+ x_t = (
858
+ (sigma_t / sigma_s0) * sample
859
+ - (alpha_t * (torch.exp(-h) - 1.0)) * D0
860
+ + (alpha_t * ((torch.exp(-h) - 1.0) / h + 1.0)) * D1
861
+ - (alpha_t * ((torch.exp(-h) - 1.0 + h) / h**2 - 0.5)) * D2
862
+ )
863
+ elif self.config.algorithm_type == "dpmsolver":
864
+ # See https://arxiv.org/abs/2206.00927 for detailed derivations
865
+ x_t = (
866
+ (alpha_t / alpha_s0) * sample
867
+ - (sigma_t * (torch.exp(h) - 1.0)) * D0
868
+ - (sigma_t * ((torch.exp(h) - 1.0) / h - 1.0)) * D1
869
+ - (sigma_t * ((torch.exp(h) - 1.0 - h) / h**2 - 0.5)) * D2
870
+ )
871
+ elif self.config.algorithm_type == "sde-dpmsolver++":
872
+ assert noise is not None
873
+ x_t = (
874
+ (sigma_t / sigma_s0 * torch.exp(-h)) * sample
875
+ + (alpha_t * (1.0 - torch.exp(-2.0 * h))) * D0
876
+ + (alpha_t * ((1.0 - torch.exp(-2.0 * h)) / (-2.0 * h) + 1.0)) * D1
877
+ + (alpha_t * ((1.0 - torch.exp(-2.0 * h) - 2.0 * h) / (2.0 * h) ** 2 - 0.5)) * D2
878
+ + sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise
879
+ )
880
+ return x_t
881
+
882
+ def index_for_timestep(self, timestep, schedule_timesteps=None):
883
+ if schedule_timesteps is None:
884
+ schedule_timesteps = self.timesteps
885
+
886
+ index_candidates = (schedule_timesteps == timestep).nonzero()
887
+
888
+ if len(index_candidates) == 0:
889
+ step_index = len(self.timesteps) - 1
890
+ # The sigma index that is taken for the **very** first `step`
891
+ # is always the second index (or the last index if there is only 1)
892
+ # This way we can ensure we don't accidentally skip a sigma in
893
+ # case we start in the middle of the denoising schedule (e.g. for image-to-image)
894
+ elif len(index_candidates) > 1:
895
+ step_index = index_candidates[1].item()
896
+ else:
897
+ step_index = index_candidates[0].item()
898
+
899
+ return step_index
900
+
901
+ def _init_step_index(self, timestep):
902
+ """
903
+ Initialize the step_index counter for the scheduler.
904
+ """
905
+
906
+ if self.begin_index is None:
907
+ if isinstance(timestep, torch.Tensor):
908
+ timestep = timestep.to(self.timesteps.device)
909
+ self._step_index = self.index_for_timestep(timestep)
910
+ else:
911
+ self._step_index = self._begin_index
912
+
913
+ def step(
914
+ self,
915
+ model_output: torch.Tensor,
916
+ timestep: Union[int, torch.Tensor],
917
+ sample: torch.Tensor,
918
+ generator=None,
919
+ variance_noise: Optional[torch.Tensor] = None,
920
+ return_dict: bool = True,
921
+ ) -> Union[SchedulerOutput, Tuple]:
922
+ """
923
+ Predict the sample from the previous timestep by reversing the SDE. This function propagates the sample with
924
+ the multistep DPMSolver.
925
+
926
+ Args:
927
+ model_output (`torch.Tensor`):
928
+ The direct output from learned diffusion model.
929
+ timestep (`int`):
930
+ The current discrete timestep in the diffusion chain.
931
+ sample (`torch.Tensor`):
932
+ A current instance of a sample created by the diffusion process.
933
+ generator (`torch.Generator`, *optional*):
934
+ A random number generator.
935
+ variance_noise (`torch.Tensor`):
936
+ Alternative to generating noise with `generator` by directly providing the noise for the variance
937
+ itself. Useful for methods such as [`LEdits++`].
938
+ return_dict (`bool`):
939
+ Whether or not to return a [`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`.
940
+
941
+ Returns:
942
+ [`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`:
943
+ If return_dict is `True`, [`~schedulers.scheduling_utils.SchedulerOutput`] is returned, otherwise a
944
+ tuple is returned where the first element is the sample tensor.
945
+
946
+ """
947
+ if self.num_inference_steps is None:
948
+ raise ValueError(
949
+ "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
950
+ )
951
+
952
+ if self.step_index is None:
953
+ self._init_step_index(timestep)
954
+
955
+ # Improve numerical stability for small number of steps
956
+ lower_order_final = (self.step_index == len(self.timesteps) - 1) and (
957
+ self.config.euler_at_final
958
+ or (self.config.lower_order_final and len(self.timesteps) < 15)
959
+ or self.config.final_sigmas_type == "zero"
960
+ )
961
+ lower_order_second = (
962
+ (self.step_index == len(self.timesteps) - 2) and self.config.lower_order_final and len(self.timesteps) < 15
963
+ )
964
+
965
+ model_output = self.convert_model_output(model_output, sample=sample)
966
+ for i in range(self.config.solver_order - 1):
967
+ self.model_outputs[i] = self.model_outputs[i + 1]
968
+ self.model_outputs[-1] = model_output
969
+
970
+ # Upcast to avoid precision issues when computing prev_sample
971
+ sample = sample.to(torch.float32)
972
+ if self.config.algorithm_type in ["sde-dpmsolver", "sde-dpmsolver++"] and variance_noise is None:
973
+ noise = randn_tensor(
974
+ model_output.shape, generator=generator, device=model_output.device, dtype=torch.float32
975
+ )
976
+ elif self.config.algorithm_type in ["sde-dpmsolver", "sde-dpmsolver++"]:
977
+ noise = variance_noise.to(device=model_output.device, dtype=torch.float32)
978
+ else:
979
+ noise = None
980
+
981
+ if self.config.solver_order == 1 or self.lower_order_nums < 1 or lower_order_final:
982
+ prev_sample = self.dpm_solver_first_order_update(model_output, sample=sample, noise=noise)
983
+ elif self.config.solver_order == 2 or self.lower_order_nums < 2 or lower_order_second:
984
+ prev_sample = self.multistep_dpm_solver_second_order_update(self.model_outputs, sample=sample, noise=noise)
985
+ else:
986
+ prev_sample = self.multistep_dpm_solver_third_order_update(self.model_outputs, sample=sample, noise=noise)
987
+
988
+ if self.lower_order_nums < self.config.solver_order:
989
+ self.lower_order_nums += 1
990
+
991
+ # Cast sample back to expected dtype
992
+ prev_sample = prev_sample.to(model_output.dtype)
993
+
994
+ # upon completion increase step index by one
995
+ self._step_index += 1
996
+
997
+ if not return_dict:
998
+ return (prev_sample,)
999
+
1000
+ return SchedulerOutput(prev_sample=prev_sample)
1001
+
1002
+ def scale_model_input(self, sample: torch.Tensor, *args, **kwargs) -> torch.Tensor:
1003
+ """
1004
+ Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
1005
+ current timestep.
1006
+
1007
+ Args:
1008
+ sample (`torch.Tensor`):
1009
+ The input sample.
1010
+
1011
+ Returns:
1012
+ `torch.Tensor`:
1013
+ A scaled input sample.
1014
+ """
1015
+ return sample
1016
+
1017
+ def add_noise(
1018
+ self,
1019
+ original_samples: torch.Tensor,
1020
+ noise: torch.Tensor,
1021
+ timesteps: torch.IntTensor,
1022
+ ) -> torch.Tensor:
1023
+ # Make sure sigmas and timesteps have the same device and dtype as original_samples
1024
+ sigmas = self.sigmas.to(device=original_samples.device, dtype=original_samples.dtype)
1025
+ if original_samples.device.type == "mps" and torch.is_floating_point(timesteps):
1026
+ # mps does not support float64
1027
+ schedule_timesteps = self.timesteps.to(original_samples.device, dtype=torch.float32)
1028
+ timesteps = timesteps.to(original_samples.device, dtype=torch.float32)
1029
+ else:
1030
+ schedule_timesteps = self.timesteps.to(original_samples.device)
1031
+ timesteps = timesteps.to(original_samples.device)
1032
+
1033
+ # begin_index is None when the scheduler is used for training or pipeline does not implement set_begin_index
1034
+ if self.begin_index is None:
1035
+ step_indices = [self.index_for_timestep(t, schedule_timesteps) for t in timesteps]
1036
+ elif self.step_index is not None:
1037
+ # add_noise is called after first denoising step (for inpainting)
1038
+ step_indices = [self.step_index] * timesteps.shape[0]
1039
+ else:
1040
+ # add noise is called before first denoising step to create initial latent(img2img)
1041
+ step_indices = [self.begin_index] * timesteps.shape[0]
1042
+
1043
+ sigma = sigmas[step_indices].flatten()
1044
+ while len(sigma.shape) < len(original_samples.shape):
1045
+ sigma = sigma.unsqueeze(-1)
1046
+
1047
+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma)
1048
+ noisy_samples = alpha_t * original_samples + sigma_t * noise
1049
+ return noisy_samples
1050
+
1051
+ def __len__(self):
1052
+ return self.config.num_train_timesteps