clone3 commited on
Commit
2af63db
·
verified ·
1 Parent(s): 8635465

Delete lcm_scheduler.py

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