SingleZombie commited on
Commit
b0ba163
·
verified ·
1 Parent(s): 87f1b8f

Create i2sb_scheduler.py

Browse files
Files changed (1) hide show
  1. scheduler/i2sb_scheduler.py +531 -0
scheduler/i2sb_scheduler.py ADDED
@@ -0,0 +1,531 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 UC Berkeley 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/ermongroup/ddim
16
+
17
+ import math
18
+ from dataclasses import dataclass
19
+ from typing import List, Optional, Tuple, Union
20
+
21
+ import numpy as np
22
+ import torch
23
+
24
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
25
+ from diffusers.utils import BaseOutput
26
+ from diffusers.utils.torch_utils import randn_tensor
27
+ from diffusers.schedulers.scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin
28
+
29
+
30
+ @dataclass
31
+ class DDPMSchedulerOutput(BaseOutput):
32
+ """
33
+ Output class for the scheduler's `step` function output.
34
+
35
+ Args:
36
+ prev_sample (`torch.Tensor` of shape `(batch_size, num_channels, height, width)` for images):
37
+ Computed sample `(x_{t-1})` of previous timestep. `prev_sample` should be used as next model input in the
38
+ denoising loop.
39
+ pred_original_sample (`torch.Tensor` 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
+ prev_sample: torch.Tensor
45
+ pred_original_sample: Optional[torch.Tensor] = None
46
+
47
+
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
+
57
+ Contains a function alpha_bar that takes an argument t and transforms it to the cumulative product of (1-beta) up
58
+ to that part of the diffusion process.
59
+
60
+
61
+ Args:
62
+ num_diffusion_timesteps (`int`): the number of betas to produce.
63
+ max_beta (`float`): the maximum beta to use; use values lower than 1 to
64
+ prevent singularities.
65
+ alpha_transform_type (`str`, *optional*, default to `cosine`): the type of noise schedule for alpha_bar.
66
+ Choose from `cosine` or `exp`
67
+
68
+ Returns:
69
+ betas (`np.ndarray`): the betas used by the scheduler to step the model outputs
70
+ """
71
+ if alpha_transform_type == "cosine":
72
+
73
+ def alpha_bar_fn(t):
74
+ return math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2
75
+
76
+ elif alpha_transform_type == "exp":
77
+
78
+ def alpha_bar_fn(t):
79
+ return math.exp(t * -12.0)
80
+
81
+ else:
82
+ raise ValueError(
83
+ f"Unsupported alpha_transform_type: {alpha_transform_type}")
84
+
85
+ betas = []
86
+ for i in range(num_diffusion_timesteps):
87
+ t1 = i / num_diffusion_timesteps
88
+ t2 = (i + 1) / num_diffusion_timesteps
89
+ betas.append(min(1 - alpha_bar_fn(t2) / alpha_bar_fn(t1), max_beta))
90
+ return torch.tensor(betas, dtype=torch.float32)
91
+
92
+
93
+ # Copied from diffusers.schedulers.scheduling_ddim.rescale_zero_terminal_snr
94
+ def rescale_zero_terminal_snr(betas):
95
+ """
96
+ Rescales betas to have zero terminal SNR Based on https://arxiv.org/pdf/2305.08891.pdf (Algorithm 1)
97
+
98
+
99
+ Args:
100
+ betas (`torch.Tensor`):
101
+ the betas that the scheduler is being initialized with.
102
+
103
+ Returns:
104
+ `torch.Tensor`: rescaled betas with zero terminal SNR
105
+ """
106
+ # Convert betas to alphas_bar_sqrt
107
+ alphas = 1.0 - betas
108
+ alphas_cumprod = torch.cumprod(alphas, dim=0)
109
+ alphas_bar_sqrt = alphas_cumprod.sqrt()
110
+
111
+ # Store old values.
112
+ alphas_bar_sqrt_0 = alphas_bar_sqrt[0].clone()
113
+ alphas_bar_sqrt_T = alphas_bar_sqrt[-1].clone()
114
+
115
+ # Shift so the last timestep is zero.
116
+ alphas_bar_sqrt -= alphas_bar_sqrt_T
117
+
118
+ # Scale so the first timestep is back to the old value.
119
+ alphas_bar_sqrt *= alphas_bar_sqrt_0 / \
120
+ (alphas_bar_sqrt_0 - alphas_bar_sqrt_T)
121
+
122
+ # Convert alphas_bar_sqrt to betas
123
+ alphas_bar = alphas_bar_sqrt**2 # Revert sqrt
124
+ alphas = alphas_bar[1:] / alphas_bar[:-1] # Revert cumprod
125
+ alphas = torch.cat([alphas_bar[0:1], alphas])
126
+ betas = 1 - alphas
127
+
128
+ return betas
129
+
130
+
131
+ def compute_gaussian_product_coef(sigma1, sigma2):
132
+ """ Given p1 = N(x_t|x_0, sigma_1**2) and p2 = N(x_t|x_1, sigma_2**2)
133
+ return p1 * p2 = N(x_t| coef1 * x0 + coef2 * x1, var) """
134
+
135
+ denom = sigma1**2 + sigma2**2
136
+ coef1 = sigma2**2 / denom
137
+ coef2 = sigma1**2 / denom
138
+ var = (sigma1**2 * sigma2**2) / denom
139
+ return coef1, coef2, var
140
+
141
+
142
+ class I2SBScheduler(SchedulerMixin, ConfigMixin):
143
+
144
+ @register_to_config
145
+ def __init__(
146
+ self,
147
+ num_train_timesteps: int = 1000,
148
+ beta_start: float = 0.0001,
149
+ beta_end: float = 0.02,
150
+ beta_schedule: str = "linear",
151
+ trained_betas: Optional[Union[np.ndarray, List[float]]] = None,
152
+ variance_type: str = "fixed_small",
153
+ clip_sample: bool = True,
154
+ prediction_type: str = "epsilon",
155
+ thresholding: bool = False,
156
+ dynamic_thresholding_ratio: float = 0.995,
157
+ clip_sample_range: float = 1.0,
158
+ sample_max_value: float = 1.0,
159
+ timestep_spacing: str = "leading",
160
+ steps_offset: int = 0,
161
+ rescale_betas_zero_snr: bool = False,
162
+ ):
163
+ if trained_betas is not None:
164
+ self.betas = torch.tensor(trained_betas, dtype=torch.float32)
165
+ elif beta_schedule == "linear":
166
+ self.betas = torch.linspace(
167
+ beta_start, beta_end, num_train_timesteps, dtype=torch.float32)
168
+ elif beta_schedule == "scaled_linear":
169
+ # this schedule is very specific to the latent diffusion model.
170
+ self.betas = torch.linspace(
171
+ beta_start**0.5, beta_end**0.5, num_train_timesteps, dtype=torch.float32) ** 2
172
+ elif beta_schedule == "squaredcos_cap_v2":
173
+ # Glide cosine schedule
174
+ self.betas = betas_for_alpha_bar(num_train_timesteps)
175
+ elif beta_schedule == "sigmoid":
176
+ # GeoDiff sigmoid schedule
177
+ betas = torch.linspace(-6, 6, num_train_timesteps)
178
+ self.betas = torch.sigmoid(
179
+ betas) * (beta_end - beta_start) + beta_start
180
+ else:
181
+ raise NotImplementedError(
182
+ f"{beta_schedule} is not implemented for {self.__class__}")
183
+
184
+ # Rescale for zero SNR
185
+ if rescale_betas_zero_snr:
186
+ self.betas = rescale_zero_terminal_snr(self.betas)
187
+
188
+ std_fwd = torch.sqrt(torch.cumsum(self.betas, 0))
189
+ std_bwd = torch.sqrt(torch.flip(
190
+ torch.cumsum(torch.flip(self.betas, dims=[0]), 0), dims=[0]))
191
+ mu_x0, mu_x1, var = compute_gaussian_product_coef(std_fwd, std_bwd)
192
+ std_sb = torch.sqrt(var)
193
+ self.std_fwd = std_fwd
194
+ self.std_bwd = std_bwd
195
+ self.std_sb = std_sb
196
+ self.mu_x0 = mu_x0
197
+ self.mu_x1 = mu_x1
198
+
199
+ # setable values
200
+ self.custom_timesteps = False
201
+ self.num_inference_steps = None
202
+ self.timesteps = torch.from_numpy(
203
+ np.arange(0, num_train_timesteps)[::-1].copy())
204
+
205
+ self.variance_type = variance_type
206
+
207
+ def scale_model_input(self, sample: torch.Tensor, timestep: Optional[int] = None) -> torch.Tensor:
208
+ """
209
+ Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
210
+ current timestep.
211
+
212
+ Args:
213
+ sample (`torch.Tensor`):
214
+ The input sample.
215
+ timestep (`int`, *optional*):
216
+ The current timestep in the diffusion chain.
217
+
218
+ Returns:
219
+ `torch.Tensor`:
220
+ A scaled input sample.
221
+ """
222
+ return sample
223
+
224
+ def set_timesteps(
225
+ self,
226
+ num_inference_steps: Optional[int] = None,
227
+ device: Union[str, torch.device] = None,
228
+ timesteps: Optional[List[int]] = None,
229
+ ):
230
+ """
231
+ Sets the discrete timesteps used for the diffusion chain (to be run before inference).
232
+
233
+ Args:
234
+ num_inference_steps (`int`):
235
+ The number of diffusion steps used when generating samples with a pre-trained model. If used,
236
+ `timesteps` must be `None`.
237
+ device (`str` or `torch.device`, *optional*):
238
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
239
+ timesteps (`List[int]`, *optional*):
240
+ Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
241
+ timestep spacing strategy of equal spacing between timesteps is used. If `timesteps` is passed,
242
+ `num_inference_steps` must be `None`.
243
+
244
+ """
245
+ if num_inference_steps is not None and timesteps is not None:
246
+ raise ValueError(
247
+ "Can only pass one of `num_inference_steps` or `custom_timesteps`.")
248
+
249
+ if timesteps is not None:
250
+ for i in range(1, len(timesteps)):
251
+ if timesteps[i] >= timesteps[i - 1]:
252
+ raise ValueError(
253
+ "`custom_timesteps` must be in descending order.")
254
+
255
+ if timesteps[0] >= self.config.num_train_timesteps:
256
+ raise ValueError(
257
+ f"`timesteps` must start before `self.config.train_timesteps`:"
258
+ f" {self.config.num_train_timesteps}."
259
+ )
260
+
261
+ timesteps = np.array(timesteps, dtype=np.int64)
262
+ self.custom_timesteps = True
263
+ else:
264
+ if num_inference_steps > self.config.num_train_timesteps:
265
+ raise ValueError(
266
+ f"`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:"
267
+ f" {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle"
268
+ f" maximal {self.config.num_train_timesteps} timesteps."
269
+ )
270
+
271
+ self.num_inference_steps = num_inference_steps
272
+ self.custom_timesteps = False
273
+
274
+ # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
275
+ if self.config.timestep_spacing == "linspace":
276
+ timesteps = (
277
+ np.linspace(0, self.config.num_train_timesteps -
278
+ 1, num_inference_steps)
279
+ .round()[::-1]
280
+ .copy()
281
+ .astype(np.int64)
282
+ )
283
+ elif self.config.timestep_spacing == "leading":
284
+ step_ratio = self.config.num_train_timesteps // self.num_inference_steps
285
+ # creates integer timesteps by multiplying by ratio
286
+ # casting to int to avoid issues when num_inference_step is power of 3
287
+ timesteps = (np.arange(0, num_inference_steps) *
288
+ step_ratio).round()[::-1].copy().astype(np.int64)
289
+ timesteps += self.config.steps_offset
290
+ elif self.config.timestep_spacing == "trailing":
291
+ step_ratio = self.config.num_train_timesteps / self.num_inference_steps
292
+ # creates integer timesteps by multiplying by ratio
293
+ # casting to int to avoid issues when num_inference_step is power of 3
294
+ timesteps = np.round(
295
+ np.arange(self.config.num_train_timesteps, 0, -step_ratio)).astype(np.int64)
296
+ timesteps -= 1
297
+ else:
298
+ raise ValueError(
299
+ f"{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'."
300
+ )
301
+
302
+ self.timesteps = torch.from_numpy(timesteps).to(device)
303
+
304
+ def _get_variance(self, t, predicted_variance=None, variance_type=None):
305
+ prev_t = self.previous_timestep(t)
306
+
307
+ alpha_prod_t = self.alphas_cumprod[t]
308
+ alpha_prod_t_prev = self.alphas_cumprod[prev_t] if prev_t >= 0 else self.one
309
+ current_beta_t = 1 - alpha_prod_t / alpha_prod_t_prev
310
+
311
+ # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf)
312
+ # and sample from it to get previous sample
313
+ # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample
314
+ variance = (1 - alpha_prod_t_prev) / \
315
+ (1 - alpha_prod_t) * current_beta_t
316
+
317
+ # we always take the log of variance, so clamp it to ensure it's not 0
318
+ variance = torch.clamp(variance, min=1e-20)
319
+
320
+ if variance_type is None:
321
+ variance_type = self.config.variance_type
322
+
323
+ # hacks - were probably added for training stability
324
+ if variance_type == "fixed_small":
325
+ variance = variance
326
+ # for rl-diffuser https://arxiv.org/abs/2205.09991
327
+ elif variance_type == "fixed_small_log":
328
+ variance = torch.log(variance)
329
+ variance = torch.exp(0.5 * variance)
330
+ elif variance_type == "fixed_large":
331
+ variance = current_beta_t
332
+ elif variance_type == "fixed_large_log":
333
+ # Glide max_log
334
+ variance = torch.log(current_beta_t)
335
+ elif variance_type == "learned":
336
+ return predicted_variance
337
+ elif variance_type == "learned_range":
338
+ min_log = torch.log(variance)
339
+ max_log = torch.log(current_beta_t)
340
+ frac = (predicted_variance + 1) / 2
341
+ variance = frac * max_log + (1 - frac) * min_log
342
+
343
+ return variance
344
+
345
+ def _threshold_sample(self, sample: torch.Tensor) -> torch.Tensor:
346
+ """
347
+ "Dynamic thresholding: At each sampling step we set s to a certain percentile absolute pixel value in xt0 (the
348
+ prediction of x_0 at timestep t), and if s > 1, then we threshold xt0 to the range [-s, s] and then divide by
349
+ s. Dynamic thresholding pushes saturated pixels (those near -1 and 1) inwards, thereby actively preventing
350
+ pixels from saturation at each step. We find that dynamic thresholding results in significantly better
351
+ photorealism as well as better image-text alignment, especially when using very large guidance weights."
352
+
353
+ https://arxiv.org/abs/2205.11487
354
+ """
355
+ dtype = sample.dtype
356
+ batch_size, channels, *remaining_dims = sample.shape
357
+
358
+ if dtype not in (torch.float32, torch.float64):
359
+ # upcast for quantile calculation, and clamp not implemented for cpu half
360
+ sample = sample.float()
361
+
362
+ # Flatten sample for doing quantile calculation along each image
363
+ sample = sample.reshape(batch_size, channels * np.prod(remaining_dims))
364
+
365
+ abs_sample = sample.abs() # "a certain percentile absolute pixel value"
366
+
367
+ s = torch.quantile(
368
+ abs_sample, self.config.dynamic_thresholding_ratio, dim=1)
369
+ s = torch.clamp(
370
+ s, min=1, max=self.config.sample_max_value
371
+ ) # When clamped to min=1, equivalent to standard clipping to [-1, 1]
372
+ # (batch_size, 1) because clamp will broadcast along dim=0
373
+ s = s.unsqueeze(1)
374
+ # "we threshold xt0 to the range [-s, s] and then divide by s"
375
+ sample = torch.clamp(sample, -s, s) / s
376
+
377
+ sample = sample.reshape(batch_size, channels, *remaining_dims)
378
+ sample = sample.to(dtype)
379
+
380
+ return sample
381
+
382
+ def step(
383
+ self,
384
+ model_output: torch.Tensor,
385
+ timestep: int,
386
+ sample: torch.Tensor,
387
+ is_ode: bool = False,
388
+ generator=None,
389
+ return_dict: bool = True,
390
+ ) -> Union[DDPMSchedulerOutput, Tuple]:
391
+ """
392
+ Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
393
+ process from the learned model outputs (most often the predicted noise).
394
+
395
+ Args:
396
+ model_output (`torch.Tensor`):
397
+ The direct output from learned diffusion model.
398
+ timestep (`float`):
399
+ The current discrete timestep in the diffusion chain.
400
+ sample (`torch.Tensor`):
401
+ A current instance of a sample created by the diffusion process.
402
+ generator (`torch.Generator`, *optional*):
403
+ A random number generator.
404
+ return_dict (`bool`, *optional*, defaults to `True`):
405
+ Whether or not to return a [`~schedulers.scheduling_ddpm.DDPMSchedulerOutput`] or `tuple`.
406
+
407
+ Returns:
408
+ [`~schedulers.scheduling_ddpm.DDPMSchedulerOutput`] or `tuple`:
409
+ If return_dict is `True`, [`~schedulers.scheduling_ddpm.DDPMSchedulerOutput`] is returned, otherwise a
410
+ tuple is returned where the first element is the sample tensor.
411
+
412
+ """
413
+ t = timestep
414
+
415
+ prev_t = self.previous_timestep(t)
416
+
417
+ if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]:
418
+ model_output, predicted_variance = torch.split(
419
+ model_output, sample.shape[1], dim=1)
420
+ else:
421
+ predicted_variance = None
422
+
423
+ std_fwd_list = self.std_fwd.to(device=sample.device)
424
+ std_fwd = std_fwd_list[t]
425
+ std_fwd_prev = std_fwd_list[prev_t]
426
+ std_delta = (std_fwd**2 - std_fwd_prev**2).sqrt()
427
+
428
+ pred_original_sample = sample - std_fwd * model_output
429
+
430
+ # 3. Clip or threshold "predicted x_0"
431
+ if self.config.thresholding:
432
+ pred_original_sample = self._threshold_sample(pred_original_sample)
433
+ elif self.config.clip_sample:
434
+ pred_original_sample = pred_original_sample.clamp(
435
+ -self.config.clip_sample_range, self.config.clip_sample_range
436
+ )
437
+
438
+ mu_x0, mu_xt, var = compute_gaussian_product_coef(
439
+ std_fwd_prev, std_delta)
440
+ pred_prev_sample = mu_x0 * pred_original_sample + mu_xt * sample
441
+
442
+ # 6. Add noise
443
+ variance_noise = 0
444
+ if t > 0 and not is_ode:
445
+ device = model_output.device
446
+ variance_noise = randn_tensor(
447
+ model_output.shape, generator=generator, device=device, dtype=model_output.dtype
448
+ ) * var.sqrt()
449
+
450
+ pred_prev_sample = pred_prev_sample + variance_noise
451
+
452
+ # from torchvision.utils import save_image
453
+ # img_cat = torch.cat((xn, pred_original_sample, pred_prev_sample), 2)
454
+ # save_image((img_cat + 1) / 2, f'tmp/tmp_{t.item()}.png')
455
+
456
+ if not return_dict:
457
+ return (pred_prev_sample,)
458
+
459
+ return DDPMSchedulerOutput(prev_sample=pred_prev_sample, pred_original_sample=pred_original_sample)
460
+
461
+ def add_noise(
462
+ self,
463
+ x0: torch.Tensor,
464
+ x1: torch.Tensor,
465
+ timesteps: torch.IntTensor,
466
+ is_ode: bool = False,
467
+ noise=None
468
+ ) -> torch.Tensor:
469
+ mu_x0 = self.mu_x0.to(device=x0.device)
470
+ mu_x0 = mu_x0[timesteps]
471
+ mu_x1 = self.mu_x1.to(device=x0.device)
472
+ mu_x1 = mu_x1[timesteps]
473
+ std_sb = self.std_sb.to(device=x0.device)
474
+ std_sb = std_sb[timesteps]
475
+ while len(mu_x0.shape) < len(x0.shape):
476
+ mu_x0 = mu_x0.unsqueeze(-1)
477
+ mu_x1 = mu_x1.unsqueeze(-1)
478
+ std_sb = std_sb.unsqueeze(-1)
479
+
480
+ xt = mu_x0 * x0 + mu_x1 * x1
481
+ if not is_ode:
482
+ if noise is None:
483
+ noise = torch.randn_like(xt)
484
+ xt = xt + std_sb * noise
485
+ return xt
486
+
487
+ def get_velocity(self, sample: torch.Tensor, noise: torch.Tensor, timesteps: torch.IntTensor) -> torch.Tensor:
488
+ raise NotImplementedError
489
+ # Make sure alphas_cumprod and timestep have same device and dtype as sample
490
+ # self.alphas_cumprod = self.alphas_cumprod.to(device=sample.device)
491
+ # alphas_cumprod = self.alphas_cumprod.to(dtype=sample.dtype)
492
+ # timesteps = timesteps.to(sample.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(sample.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(sample.shape):
502
+ # sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.unsqueeze(-1)
503
+
504
+ # velocity = sqrt_alpha_prod * noise - sqrt_one_minus_alpha_prod * sample
505
+ # return velocity
506
+
507
+ def compute_label(self, timesteps, x0, xt):
508
+ std_fwd = self.std_fwd.to(device=x0.device)
509
+ std_fwd = std_fwd[timesteps]
510
+ while len(std_fwd.shape) < len(x0.shape):
511
+ std_fwd = std_fwd.unsqueeze(-1)
512
+ label = (xt - x0) / std_fwd
513
+ return label
514
+
515
+ def __len__(self):
516
+ return self.config.num_train_timesteps
517
+
518
+ def previous_timestep(self, timestep):
519
+ if self.custom_timesteps:
520
+ index = (self.timesteps == timestep).nonzero(as_tuple=True)[0][0]
521
+ if index == self.timesteps.shape[0] - 1:
522
+ prev_t = torch.tensor(-1)
523
+ else:
524
+ prev_t = self.timesteps[index + 1]
525
+ else:
526
+ num_inference_steps = (
527
+ self.num_inference_steps if self.num_inference_steps else self.config.num_train_timesteps
528
+ )
529
+ prev_t = timestep - self.config.num_train_timesteps // num_inference_steps
530
+
531
+ return prev_t