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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2023 Stanford University 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 code is strongly influenced by https://github.com/pesser/pytorch_diffusion
|
16 |
+
# and https://github.com/hojonathanho/diffusion
|
17 |
+
|
18 |
+
import math
|
19 |
+
from dataclasses import dataclass
|
20 |
+
from typing import List, Optional, Tuple, Union
|
21 |
+
|
22 |
+
import numpy as np
|
23 |
+
import torch
|
24 |
+
|
25 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
26 |
+
from diffusers.utils import BaseOutput, logging
|
27 |
+
from diffusers.utils.torch_utils import randn_tensor
|
28 |
+
from diffusers.schedulers.scheduling_utils import SchedulerMixin
|
29 |
+
|
30 |
+
|
31 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
32 |
+
|
33 |
+
|
34 |
+
@dataclass
|
35 |
+
class LCMSingleStepSchedulerOutput(BaseOutput):
|
36 |
+
"""
|
37 |
+
Output class for the scheduler's `step` function output.
|
38 |
+
Args:
|
39 |
+
pred_original_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):
|
40 |
+
The predicted denoised sample `(x_{0})` based on the model output from the current timestep.
|
41 |
+
`pred_original_sample` can be used to preview progress or for guidance.
|
42 |
+
"""
|
43 |
+
|
44 |
+
denoised: Optional[torch.FloatTensor] = None
|
45 |
+
|
46 |
+
|
47 |
+
# Copied from diffusers.schedulers.scheduling_ddpm.betas_for_alpha_bar
|
48 |
+
def betas_for_alpha_bar(
|
49 |
+
num_diffusion_timesteps,
|
50 |
+
max_beta=0.999,
|
51 |
+
alpha_transform_type="cosine",
|
52 |
+
):
|
53 |
+
"""
|
54 |
+
Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of
|
55 |
+
(1-beta) over time from t = [0,1].
|
56 |
+
Contains a function alpha_bar that takes an argument t and transforms it to the cumulative product of (1-beta) up
|
57 |
+
to that part of the diffusion process.
|
58 |
+
Args:
|
59 |
+
num_diffusion_timesteps (`int`): the number of betas to produce.
|
60 |
+
max_beta (`float`): the maximum beta to use; use values lower than 1 to
|
61 |
+
prevent singularities.
|
62 |
+
alpha_transform_type (`str`, *optional*, default to `cosine`): the type of noise schedule for alpha_bar.
|
63 |
+
Choose from `cosine` or `exp`
|
64 |
+
Returns:
|
65 |
+
betas (`np.ndarray`): the betas used by the scheduler to step the model outputs
|
66 |
+
"""
|
67 |
+
if alpha_transform_type == "cosine":
|
68 |
+
|
69 |
+
def alpha_bar_fn(t):
|
70 |
+
return math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2
|
71 |
+
|
72 |
+
elif alpha_transform_type == "exp":
|
73 |
+
|
74 |
+
def alpha_bar_fn(t):
|
75 |
+
return math.exp(t * -12.0)
|
76 |
+
|
77 |
+
else:
|
78 |
+
raise ValueError(f"Unsupported alpha_tranform_type: {alpha_transform_type}")
|
79 |
+
|
80 |
+
betas = []
|
81 |
+
for i in range(num_diffusion_timesteps):
|
82 |
+
t1 = i / num_diffusion_timesteps
|
83 |
+
t2 = (i + 1) / num_diffusion_timesteps
|
84 |
+
betas.append(min(1 - alpha_bar_fn(t2) / alpha_bar_fn(t1), max_beta))
|
85 |
+
return torch.tensor(betas, dtype=torch.float32)
|
86 |
+
|
87 |
+
|
88 |
+
# Copied from diffusers.schedulers.scheduling_ddim.rescale_zero_terminal_snr
|
89 |
+
def rescale_zero_terminal_snr(betas: torch.FloatTensor) -> torch.FloatTensor:
|
90 |
+
"""
|
91 |
+
Rescales betas to have zero terminal SNR Based on https://arxiv.org/pdf/2305.08891.pdf (Algorithm 1)
|
92 |
+
Args:
|
93 |
+
betas (`torch.FloatTensor`):
|
94 |
+
the betas that the scheduler is being initialized with.
|
95 |
+
Returns:
|
96 |
+
`torch.FloatTensor`: rescaled betas with zero terminal SNR
|
97 |
+
"""
|
98 |
+
# Convert betas to alphas_bar_sqrt
|
99 |
+
alphas = 1.0 - betas
|
100 |
+
alphas_cumprod = torch.cumprod(alphas, dim=0)
|
101 |
+
alphas_bar_sqrt = alphas_cumprod.sqrt()
|
102 |
+
|
103 |
+
# Store old values.
|
104 |
+
alphas_bar_sqrt_0 = alphas_bar_sqrt[0].clone()
|
105 |
+
alphas_bar_sqrt_T = alphas_bar_sqrt[-1].clone()
|
106 |
+
|
107 |
+
# Shift so the last timestep is zero.
|
108 |
+
alphas_bar_sqrt -= alphas_bar_sqrt_T
|
109 |
+
|
110 |
+
# Scale so the first timestep is back to the old value.
|
111 |
+
alphas_bar_sqrt *= alphas_bar_sqrt_0 / (alphas_bar_sqrt_0 - alphas_bar_sqrt_T)
|
112 |
+
|
113 |
+
# Convert alphas_bar_sqrt to betas
|
114 |
+
alphas_bar = alphas_bar_sqrt**2 # Revert sqrt
|
115 |
+
alphas = alphas_bar[1:] / alphas_bar[:-1] # Revert cumprod
|
116 |
+
alphas = torch.cat([alphas_bar[0:1], alphas])
|
117 |
+
betas = 1 - alphas
|
118 |
+
|
119 |
+
return betas
|
120 |
+
|
121 |
+
|
122 |
+
class LCMSingleStepScheduler(SchedulerMixin, ConfigMixin):
|
123 |
+
"""
|
124 |
+
`LCMSingleStepScheduler` extends the denoising procedure introduced in denoising diffusion probabilistic models (DDPMs) with
|
125 |
+
non-Markovian guidance.
|
126 |
+
This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. [`~ConfigMixin`] takes care of storing all config
|
127 |
+
attributes that are passed in the scheduler's `__init__` function, such as `num_train_timesteps`. They can be
|
128 |
+
accessed via `scheduler.config.num_train_timesteps`. [`SchedulerMixin`] provides general loading and saving
|
129 |
+
functionality via the [`SchedulerMixin.save_pretrained`] and [`~SchedulerMixin.from_pretrained`] functions.
|
130 |
+
Args:
|
131 |
+
num_train_timesteps (`int`, defaults to 1000):
|
132 |
+
The number of diffusion steps to train the model.
|
133 |
+
beta_start (`float`, defaults to 0.0001):
|
134 |
+
The starting `beta` value of inference.
|
135 |
+
beta_end (`float`, defaults to 0.02):
|
136 |
+
The final `beta` value.
|
137 |
+
beta_schedule (`str`, defaults to `"linear"`):
|
138 |
+
The beta schedule, a mapping from a beta range to a sequence of betas for stepping the model. Choose from
|
139 |
+
`linear`, `scaled_linear`, or `squaredcos_cap_v2`.
|
140 |
+
trained_betas (`np.ndarray`, *optional*):
|
141 |
+
Pass an array of betas directly to the constructor to bypass `beta_start` and `beta_end`.
|
142 |
+
original_inference_steps (`int`, *optional*, defaults to 50):
|
143 |
+
The default number of inference steps used to generate a linearly-spaced timestep schedule, from which we
|
144 |
+
will ultimately take `num_inference_steps` evenly spaced timesteps to form the final timestep schedule.
|
145 |
+
clip_sample (`bool`, defaults to `True`):
|
146 |
+
Clip the predicted sample for numerical stability.
|
147 |
+
clip_sample_range (`float`, defaults to 1.0):
|
148 |
+
The maximum magnitude for sample clipping. Valid only when `clip_sample=True`.
|
149 |
+
set_alpha_to_one (`bool`, defaults to `True`):
|
150 |
+
Each diffusion step uses the alphas product value at that step and at the previous one. For the final step
|
151 |
+
there is no previous alpha. When this option is `True` the previous alpha product is fixed to `1`,
|
152 |
+
otherwise it uses the alpha value at step 0.
|
153 |
+
steps_offset (`int`, defaults to 0):
|
154 |
+
An offset added to the inference steps. You can use a combination of `offset=1` and
|
155 |
+
`set_alpha_to_one=False` to make the last step use step 0 for the previous alpha product like in Stable
|
156 |
+
Diffusion.
|
157 |
+
prediction_type (`str`, defaults to `epsilon`, *optional*):
|
158 |
+
Prediction type of the scheduler function; can be `epsilon` (predicts the noise of the diffusion process),
|
159 |
+
`sample` (directly predicts the noisy sample`) or `v_prediction` (see section 2.4 of [Imagen
|
160 |
+
Video](https://imagen.research.google/video/paper.pdf) paper).
|
161 |
+
thresholding (`bool`, defaults to `False`):
|
162 |
+
Whether to use the "dynamic thresholding" method. This is unsuitable for latent-space diffusion models such
|
163 |
+
as Stable Diffusion.
|
164 |
+
dynamic_thresholding_ratio (`float`, defaults to 0.995):
|
165 |
+
The ratio for the dynamic thresholding method. Valid only when `thresholding=True`.
|
166 |
+
sample_max_value (`float`, defaults to 1.0):
|
167 |
+
The threshold value for dynamic thresholding. Valid only when `thresholding=True`.
|
168 |
+
timestep_spacing (`str`, defaults to `"leading"`):
|
169 |
+
The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and
|
170 |
+
Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information.
|
171 |
+
timestep_scaling (`float`, defaults to 10.0):
|
172 |
+
The factor the timesteps will be multiplied by when calculating the consistency model boundary conditions
|
173 |
+
`c_skip` and `c_out`. Increasing this will decrease the approximation error (although the approximation
|
174 |
+
error at the default of `10.0` is already pretty small).
|
175 |
+
rescale_betas_zero_snr (`bool`, defaults to `False`):
|
176 |
+
Whether to rescale the betas to have zero terminal SNR. This enables the model to generate very bright and
|
177 |
+
dark samples instead of limiting it to samples with medium brightness. Loosely related to
|
178 |
+
[`--offset_noise`](https://github.com/huggingface/diffusers/blob/74fd735eb073eb1d774b1ab4154a0876eb82f055/examples/dreambooth/train_dreambooth.py#L506).
|
179 |
+
"""
|
180 |
+
|
181 |
+
order = 1
|
182 |
+
|
183 |
+
@register_to_config
|
184 |
+
def __init__(
|
185 |
+
self,
|
186 |
+
num_train_timesteps: int = 1000,
|
187 |
+
beta_start: float = 0.00085,
|
188 |
+
beta_end: float = 0.012,
|
189 |
+
beta_schedule: str = "scaled_linear",
|
190 |
+
trained_betas: Optional[Union[np.ndarray, List[float]]] = None,
|
191 |
+
original_inference_steps: int = 50,
|
192 |
+
clip_sample: bool = False,
|
193 |
+
clip_sample_range: float = 1.0,
|
194 |
+
set_alpha_to_one: bool = True,
|
195 |
+
steps_offset: int = 0,
|
196 |
+
prediction_type: str = "epsilon",
|
197 |
+
thresholding: bool = False,
|
198 |
+
dynamic_thresholding_ratio: float = 0.995,
|
199 |
+
sample_max_value: float = 1.0,
|
200 |
+
timestep_spacing: str = "leading",
|
201 |
+
timestep_scaling: float = 10.0,
|
202 |
+
rescale_betas_zero_snr: bool = False,
|
203 |
+
):
|
204 |
+
if trained_betas is not None:
|
205 |
+
self.betas = torch.tensor(trained_betas, dtype=torch.float32)
|
206 |
+
elif beta_schedule == "linear":
|
207 |
+
self.betas = torch.linspace(beta_start, beta_end, num_train_timesteps, dtype=torch.float32)
|
208 |
+
elif beta_schedule == "scaled_linear":
|
209 |
+
# this schedule is very specific to the latent diffusion model.
|
210 |
+
self.betas = (
|
211 |
+
torch.linspace(beta_start**0.5, beta_end**0.5, num_train_timesteps, dtype=torch.float32) ** 2
|
212 |
+
)
|
213 |
+
elif beta_schedule == "squaredcos_cap_v2":
|
214 |
+
# Glide cosine schedule
|
215 |
+
self.betas = betas_for_alpha_bar(num_train_timesteps)
|
216 |
+
else:
|
217 |
+
raise NotImplementedError(f"{beta_schedule} does is not implemented for {self.__class__}")
|
218 |
+
|
219 |
+
# Rescale for zero SNR
|
220 |
+
if rescale_betas_zero_snr:
|
221 |
+
self.betas = rescale_zero_terminal_snr(self.betas)
|
222 |
+
|
223 |
+
self.alphas = 1.0 - self.betas
|
224 |
+
self.alphas_cumprod = torch.cumprod(self.alphas, dim=0)
|
225 |
+
|
226 |
+
# At every step in ddim, we are looking into the previous alphas_cumprod
|
227 |
+
# For the final step, there is no previous alphas_cumprod because we are already at 0
|
228 |
+
# `set_alpha_to_one` decides whether we set this parameter simply to one or
|
229 |
+
# whether we use the final alpha of the "non-previous" one.
|
230 |
+
self.final_alpha_cumprod = torch.tensor(1.0) if set_alpha_to_one else self.alphas_cumprod[0]
|
231 |
+
|
232 |
+
# standard deviation of the initial noise distribution
|
233 |
+
self.init_noise_sigma = 1.0
|
234 |
+
|
235 |
+
# setable values
|
236 |
+
self.num_inference_steps = None
|
237 |
+
self.timesteps = torch.from_numpy(np.arange(0, num_train_timesteps)[::-1].copy().astype(np.int64))
|
238 |
+
|
239 |
+
self._step_index = None
|
240 |
+
|
241 |
+
# Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._init_step_index
|
242 |
+
def _init_step_index(self, timestep):
|
243 |
+
if isinstance(timestep, torch.Tensor):
|
244 |
+
timestep = timestep.to(self.timesteps.device)
|
245 |
+
|
246 |
+
index_candidates = (self.timesteps == timestep).nonzero()
|
247 |
+
|
248 |
+
# The sigma index that is taken for the **very** first `step`
|
249 |
+
# is always the second index (or the last index if there is only 1)
|
250 |
+
# This way we can ensure we don't accidentally skip a sigma in
|
251 |
+
# case we start in the middle of the denoising schedule (e.g. for image-to-image)
|
252 |
+
if len(index_candidates) > 1:
|
253 |
+
step_index = index_candidates[1]
|
254 |
+
else:
|
255 |
+
step_index = index_candidates[0]
|
256 |
+
|
257 |
+
self._step_index = step_index.item()
|
258 |
+
|
259 |
+
@property
|
260 |
+
def step_index(self):
|
261 |
+
return self._step_index
|
262 |
+
|
263 |
+
def scale_model_input(self, sample: torch.FloatTensor, timestep: Optional[int] = None) -> torch.FloatTensor:
|
264 |
+
"""
|
265 |
+
Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
|
266 |
+
current timestep.
|
267 |
+
Args:
|
268 |
+
sample (`torch.FloatTensor`):
|
269 |
+
The input sample.
|
270 |
+
timestep (`int`, *optional*):
|
271 |
+
The current timestep in the diffusion chain.
|
272 |
+
Returns:
|
273 |
+
`torch.FloatTensor`:
|
274 |
+
A scaled input sample.
|
275 |
+
"""
|
276 |
+
return sample
|
277 |
+
|
278 |
+
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler._threshold_sample
|
279 |
+
def _threshold_sample(self, sample: torch.FloatTensor) -> torch.FloatTensor:
|
280 |
+
"""
|
281 |
+
"Dynamic thresholding: At each sampling step we set s to a certain percentile absolute pixel value in xt0 (the
|
282 |
+
prediction of x_0 at timestep t), and if s > 1, then we threshold xt0 to the range [-s, s] and then divide by
|
283 |
+
s. Dynamic thresholding pushes saturated pixels (those near -1 and 1) inwards, thereby actively preventing
|
284 |
+
pixels from saturation at each step. We find that dynamic thresholding results in significantly better
|
285 |
+
photorealism as well as better image-text alignment, especially when using very large guidance weights."
|
286 |
+
https://arxiv.org/abs/2205.11487
|
287 |
+
"""
|
288 |
+
dtype = sample.dtype
|
289 |
+
batch_size, channels, *remaining_dims = sample.shape
|
290 |
+
|
291 |
+
if dtype not in (torch.float32, torch.float64):
|
292 |
+
sample = sample.float() # upcast for quantile calculation, and clamp not implemented for cpu half
|
293 |
+
|
294 |
+
# Flatten sample for doing quantile calculation along each image
|
295 |
+
sample = sample.reshape(batch_size, channels * np.prod(remaining_dims))
|
296 |
+
|
297 |
+
abs_sample = sample.abs() # "a certain percentile absolute pixel value"
|
298 |
+
|
299 |
+
s = torch.quantile(abs_sample, self.config.dynamic_thresholding_ratio, dim=1)
|
300 |
+
s = torch.clamp(
|
301 |
+
s, min=1, max=self.config.sample_max_value
|
302 |
+
) # When clamped to min=1, equivalent to standard clipping to [-1, 1]
|
303 |
+
s = s.unsqueeze(1) # (batch_size, 1) because clamp will broadcast along dim=0
|
304 |
+
sample = torch.clamp(sample, -s, s) / s # "we threshold xt0 to the range [-s, s] and then divide by s"
|
305 |
+
|
306 |
+
sample = sample.reshape(batch_size, channels, *remaining_dims)
|
307 |
+
sample = sample.to(dtype)
|
308 |
+
|
309 |
+
return sample
|
310 |
+
|
311 |
+
def set_timesteps(
|
312 |
+
self,
|
313 |
+
num_inference_steps: int = None,
|
314 |
+
device: Union[str, torch.device] = None,
|
315 |
+
original_inference_steps: Optional[int] = None,
|
316 |
+
strength: int = 1.0,
|
317 |
+
timesteps: Optional[list] = None,
|
318 |
+
):
|
319 |
+
"""
|
320 |
+
Sets the discrete timesteps used for the diffusion chain (to be run before inference).
|
321 |
+
Args:
|
322 |
+
num_inference_steps (`int`):
|
323 |
+
The number of diffusion steps used when generating samples with a pre-trained model.
|
324 |
+
device (`str` or `torch.device`, *optional*):
|
325 |
+
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
326 |
+
original_inference_steps (`int`, *optional*):
|
327 |
+
The original number of inference steps, which will be used to generate a linearly-spaced timestep
|
328 |
+
schedule (which is different from the standard `diffusers` implementation). We will then take
|
329 |
+
`num_inference_steps` timesteps from this schedule, evenly spaced in terms of indices, and use that as
|
330 |
+
our final timestep schedule. If not set, this will default to the `original_inference_steps` attribute.
|
331 |
+
"""
|
332 |
+
|
333 |
+
if num_inference_steps is not None and timesteps is not None:
|
334 |
+
raise ValueError("Can only pass one of `num_inference_steps` or `custom_timesteps`.")
|
335 |
+
|
336 |
+
if timesteps is not None:
|
337 |
+
for i in range(1, len(timesteps)):
|
338 |
+
if timesteps[i] >= timesteps[i - 1]:
|
339 |
+
raise ValueError("`custom_timesteps` must be in descending order.")
|
340 |
+
|
341 |
+
if timesteps[0] >= self.config.num_train_timesteps:
|
342 |
+
raise ValueError(
|
343 |
+
f"`timesteps` must start before `self.config.train_timesteps`:"
|
344 |
+
f" {self.config.num_train_timesteps}."
|
345 |
+
)
|
346 |
+
|
347 |
+
timesteps = np.array(timesteps, dtype=np.int64)
|
348 |
+
else:
|
349 |
+
if num_inference_steps > self.config.num_train_timesteps:
|
350 |
+
raise ValueError(
|
351 |
+
f"`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:"
|
352 |
+
f" {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle"
|
353 |
+
f" maximal {self.config.num_train_timesteps} timesteps."
|
354 |
+
)
|
355 |
+
|
356 |
+
self.num_inference_steps = num_inference_steps
|
357 |
+
original_steps = (
|
358 |
+
original_inference_steps if original_inference_steps is not None else self.config.original_inference_steps
|
359 |
+
)
|
360 |
+
|
361 |
+
if original_steps > self.config.num_train_timesteps:
|
362 |
+
raise ValueError(
|
363 |
+
f"`original_steps`: {original_steps} cannot be larger than `self.config.train_timesteps`:"
|
364 |
+
f" {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle"
|
365 |
+
f" maximal {self.config.num_train_timesteps} timesteps."
|
366 |
+
)
|
367 |
+
|
368 |
+
if num_inference_steps > original_steps:
|
369 |
+
raise ValueError(
|
370 |
+
f"`num_inference_steps`: {num_inference_steps} cannot be larger than `original_inference_steps`:"
|
371 |
+
f" {original_steps} because the final timestep schedule will be a subset of the"
|
372 |
+
f" `original_inference_steps`-sized initial timestep schedule."
|
373 |
+
)
|
374 |
+
|
375 |
+
# LCM Timesteps Setting
|
376 |
+
# Currently, only linear spacing is supported.
|
377 |
+
c = self.config.num_train_timesteps // original_steps
|
378 |
+
# LCM Training Steps Schedule
|
379 |
+
lcm_origin_timesteps = np.asarray(list(range(1, int(original_steps * strength) + 1))) * c - 1
|
380 |
+
skipping_step = len(lcm_origin_timesteps) // num_inference_steps
|
381 |
+
# LCM Inference Steps Schedule
|
382 |
+
timesteps = lcm_origin_timesteps[::-skipping_step][:num_inference_steps]
|
383 |
+
|
384 |
+
self.timesteps = torch.from_numpy(timesteps.copy()).to(device=device, dtype=torch.long)
|
385 |
+
|
386 |
+
self._step_index = None
|
387 |
+
|
388 |
+
def get_scalings_for_boundary_condition_discrete(self, timestep):
|
389 |
+
self.sigma_data = 0.5 # Default: 0.5
|
390 |
+
scaled_timestep = timestep * self.config.timestep_scaling
|
391 |
+
|
392 |
+
c_skip = self.sigma_data**2 / (scaled_timestep**2 + self.sigma_data**2)
|
393 |
+
c_out = scaled_timestep / (scaled_timestep**2 + self.sigma_data**2) ** 0.5
|
394 |
+
return c_skip, c_out
|
395 |
+
|
396 |
+
def append_dims(self, x, target_dims):
|
397 |
+
"""Appends dimensions to the end of a tensor until it has target_dims dimensions."""
|
398 |
+
dims_to_append = target_dims - x.ndim
|
399 |
+
if dims_to_append < 0:
|
400 |
+
raise ValueError(f"input has {x.ndim} dims but target_dims is {target_dims}, which is less")
|
401 |
+
return x[(...,) + (None,) * dims_to_append]
|
402 |
+
|
403 |
+
def extract_into_tensor(self, a, t, x_shape):
|
404 |
+
b, *_ = t.shape
|
405 |
+
out = a.gather(-1, t)
|
406 |
+
return out.reshape(b, *((1,) * (len(x_shape) - 1)))
|
407 |
+
|
408 |
+
def step(
|
409 |
+
self,
|
410 |
+
model_output: torch.FloatTensor,
|
411 |
+
timestep: torch.Tensor,
|
412 |
+
sample: torch.FloatTensor,
|
413 |
+
generator: Optional[torch.Generator] = None,
|
414 |
+
return_dict: bool = True,
|
415 |
+
) -> Union[LCMSingleStepSchedulerOutput, Tuple]:
|
416 |
+
"""
|
417 |
+
Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
|
418 |
+
process from the learned model outputs (most often the predicted noise).
|
419 |
+
Args:
|
420 |
+
model_output (`torch.FloatTensor`):
|
421 |
+
The direct output from learned diffusion model.
|
422 |
+
timestep (`float`):
|
423 |
+
The current discrete timestep in the diffusion chain.
|
424 |
+
sample (`torch.FloatTensor`):
|
425 |
+
A current instance of a sample created by the diffusion process.
|
426 |
+
generator (`torch.Generator`, *optional*):
|
427 |
+
A random number generator.
|
428 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
429 |
+
Whether or not to return a [`~schedulers.scheduling_lcm.LCMSchedulerOutput`] or `tuple`.
|
430 |
+
Returns:
|
431 |
+
[`~schedulers.scheduling_utils.LCMSchedulerOutput`] or `tuple`:
|
432 |
+
If return_dict is `True`, [`~schedulers.scheduling_lcm.LCMSchedulerOutput`] is returned, otherwise a
|
433 |
+
tuple is returned where the first element is the sample tensor.
|
434 |
+
"""
|
435 |
+
# 0. make sure everything is on the same device
|
436 |
+
alphas_cumprod = self.alphas_cumprod.to(sample.device)
|
437 |
+
|
438 |
+
# 1. compute alphas, betas
|
439 |
+
if timestep.ndim == 0:
|
440 |
+
timestep = timestep.unsqueeze(0)
|
441 |
+
alpha_prod_t = self.extract_into_tensor(alphas_cumprod, timestep, sample.shape)
|
442 |
+
beta_prod_t = 1 - alpha_prod_t
|
443 |
+
|
444 |
+
# 2. Get scalings for boundary conditions
|
445 |
+
c_skip, c_out = self.get_scalings_for_boundary_condition_discrete(timestep)
|
446 |
+
c_skip, c_out = [self.append_dims(x, sample.ndim) for x in [c_skip, c_out]]
|
447 |
+
|
448 |
+
# 3. Compute the predicted original sample x_0 based on the model parameterization
|
449 |
+
if self.config.prediction_type == "epsilon": # noise-prediction
|
450 |
+
predicted_original_sample = (sample - torch.sqrt(beta_prod_t) * model_output) / torch.sqrt(alpha_prod_t)
|
451 |
+
elif self.config.prediction_type == "sample": # x-prediction
|
452 |
+
predicted_original_sample = model_output
|
453 |
+
elif self.config.prediction_type == "v_prediction": # v-prediction
|
454 |
+
predicted_original_sample = torch.sqrt(alpha_prod_t) * sample - torch.sqrt(beta_prod_t) * model_output
|
455 |
+
else:
|
456 |
+
raise ValueError(
|
457 |
+
f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` or"
|
458 |
+
" `v_prediction` for `LCMScheduler`."
|
459 |
+
)
|
460 |
+
|
461 |
+
# 4. Clip or threshold "predicted x_0"
|
462 |
+
if self.config.thresholding:
|
463 |
+
predicted_original_sample = self._threshold_sample(predicted_original_sample)
|
464 |
+
elif self.config.clip_sample:
|
465 |
+
predicted_original_sample = predicted_original_sample.clamp(
|
466 |
+
-self.config.clip_sample_range, self.config.clip_sample_range
|
467 |
+
)
|
468 |
+
|
469 |
+
# 5. Denoise model output using boundary conditions
|
470 |
+
denoised = c_out * predicted_original_sample + c_skip * sample
|
471 |
+
|
472 |
+
if not return_dict:
|
473 |
+
return (denoised, )
|
474 |
+
|
475 |
+
return LCMSingleStepSchedulerOutput(denoised=denoised)
|
476 |
+
|
477 |
+
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler.add_noise
|
478 |
+
def add_noise(
|
479 |
+
self,
|
480 |
+
original_samples: torch.FloatTensor,
|
481 |
+
noise: torch.FloatTensor,
|
482 |
+
timesteps: torch.IntTensor,
|
483 |
+
) -> torch.FloatTensor:
|
484 |
+
# Make sure alphas_cumprod and timestep have same device and dtype as original_samples
|
485 |
+
alphas_cumprod = self.alphas_cumprod.to(device=original_samples.device, dtype=original_samples.dtype)
|
486 |
+
timesteps = timesteps.to(original_samples.device)
|
487 |
+
|
488 |
+
sqrt_alpha_prod = alphas_cumprod[timesteps] ** 0.5
|
489 |
+
sqrt_alpha_prod = sqrt_alpha_prod.flatten()
|
490 |
+
while len(sqrt_alpha_prod.shape) < len(original_samples.shape):
|
491 |
+
sqrt_alpha_prod = sqrt_alpha_prod.unsqueeze(-1)
|
492 |
+
|
493 |
+
sqrt_one_minus_alpha_prod = (1 - alphas_cumprod[timesteps]) ** 0.5
|
494 |
+
sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.flatten()
|
495 |
+
while len(sqrt_one_minus_alpha_prod.shape) < len(original_samples.shape):
|
496 |
+
sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.unsqueeze(-1)
|
497 |
+
|
498 |
+
noisy_samples = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise
|
499 |
+
return noisy_samples
|
500 |
+
|
501 |
+
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler.get_velocity
|
502 |
+
def get_velocity(
|
503 |
+
self, sample: torch.FloatTensor, noise: torch.FloatTensor, timesteps: torch.IntTensor
|
504 |
+
) -> torch.FloatTensor:
|
505 |
+
# Make sure alphas_cumprod and timestep have same device and dtype as sample
|
506 |
+
alphas_cumprod = self.alphas_cumprod.to(device=sample.device, dtype=sample.dtype)
|
507 |
+
timesteps = timesteps.to(sample.device)
|
508 |
+
|
509 |
+
sqrt_alpha_prod = alphas_cumprod[timesteps] ** 0.5
|
510 |
+
sqrt_alpha_prod = sqrt_alpha_prod.flatten()
|
511 |
+
while len(sqrt_alpha_prod.shape) < len(sample.shape):
|
512 |
+
sqrt_alpha_prod = sqrt_alpha_prod.unsqueeze(-1)
|
513 |
+
|
514 |
+
sqrt_one_minus_alpha_prod = (1 - alphas_cumprod[timesteps]) ** 0.5
|
515 |
+
sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.flatten()
|
516 |
+
while len(sqrt_one_minus_alpha_prod.shape) < len(sample.shape):
|
517 |
+
sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.unsqueeze(-1)
|
518 |
+
|
519 |
+
velocity = sqrt_alpha_prod * noise - sqrt_one_minus_alpha_prod * sample
|
520 |
+
return velocity
|
521 |
+
|
522 |
+
def __len__(self):
|
523 |
+
return self.config.num_train_timesteps
|