giulio98 commited on
Commit
6ea92c4
·
verified ·
1 Parent(s): 49a937e

Create edm_euler_scheduler.py

Browse files
Files changed (1) hide show
  1. scheduler/edm_euler_scheduler.py +352 -0
scheduler/edm_euler_scheduler.py ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Optional, Tuple, Union
5
+ import torch
6
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
7
+ from diffusers.utils import BaseOutput
8
+ from diffusers.utils.torch_utils import randn_tensor
9
+ from diffusers.schedulers.scheduling_utils import SchedulerMixin, SchedulerOutput
10
+
11
+ class FixedEDMEulerScheduler(SchedulerMixin, ConfigMixin):
12
+ """
13
+ Implements the Euler scheduler in EDM formulation as presented in Karras et al. 2022 [1].
14
+
15
+ [1] Karras, Tero, et al. "Elucidating the Design Space of Diffusion-Based Generative Models."
16
+ https://arxiv.org/abs/2206.00364
17
+
18
+ This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
19
+ methods the library implements for all schedulers such as loading and saving.
20
+
21
+ Args:
22
+ sigma_min (`float`, *optional*, defaults to 0.002):
23
+ Minimum noise magnitude in the sigma schedule. This was set to 0.002 in the EDM paper [1]; a reasonable
24
+ range is [0, 10].
25
+ sigma_max (`float`, *optional*, defaults to 80.0):
26
+ Maximum noise magnitude in the sigma schedule. This was set to 80.0 in the EDM paper [1]; a reasonable
27
+ range is [0.2, 80.0].
28
+ sigma_data (`float`, *optional*, defaults to 0.5):
29
+ The standard deviation of the data distribution. This is set to 0.5 in the EDM paper [1].
30
+ num_train_timesteps (`int`, defaults to 1000):
31
+ The number of diffusion steps to train the model.
32
+ prediction_type (`str`, defaults to `epsilon`, *optional*):
33
+ Prediction type of the scheduler function; can be `epsilon` (predicts the noise of the diffusion process),
34
+ `sample` (directly predicts the noisy sample`) or `v_prediction` (see section 2.4 of [Imagen
35
+ Video](https://imagen.research.google/video/paper.pdf) paper).
36
+ rho (`float`, *optional*, defaults to 7.0):
37
+ The rho parameter used for calculating the Karras sigma schedule, which is set to 7.0 in the EDM paper [1].
38
+ """
39
+
40
+ _compatibles = []
41
+ order = 1
42
+
43
+ @register_to_config
44
+ def __init__(
45
+ self,
46
+ sigma_min: float = 0.002,
47
+ sigma_max: float = 80.0,
48
+ sigma_data: float = 0.5,
49
+ num_train_timesteps: int = 1000,
50
+ prediction_type: str = "epsilon",
51
+ rho: float = 7.0,
52
+ ):
53
+ # setable values
54
+ self.num_inference_steps = None
55
+
56
+ ramp = torch.linspace(0, 1, num_train_timesteps)
57
+ sigmas = self._compute_sigmas(ramp)
58
+ self.timesteps = self.precondition_noise(sigmas)
59
+
60
+ self.sigmas = torch.cat([sigmas, torch.zeros(1, device=sigmas.device)])
61
+
62
+ self.is_scale_input_called = False
63
+
64
+ self._step_index = None
65
+ self._begin_index = None
66
+ self.sigmas = self.sigmas.to("cpu") # to avoid too much CPU/GPU communication
67
+
68
+ @property
69
+ def init_noise_sigma(self):
70
+ # standard deviation of the initial noise distribution
71
+ return (self.config.sigma_max **2 + 1) ** 0.5
72
+
73
+ @property
74
+ def step_index(self):
75
+ """
76
+ The index counter for current timestep. It will increae 1 after each scheduler step.
77
+ """
78
+ return self._step_index
79
+
80
+ @property
81
+ def begin_index(self):
82
+ """
83
+ The index for the first timestep. It should be set from pipeline with `set_begin_index` method.
84
+ """
85
+ return self._begin_index
86
+
87
+ # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.set_begin_index
88
+ def set_begin_index(self, begin_index: int = 0):
89
+ """
90
+ Sets the begin index for the scheduler. This function should be run from pipeline before the inference.
91
+
92
+ Args:
93
+ begin_index (`int`):
94
+ The begin index for the scheduler.
95
+ """
96
+ self._begin_index = begin_index
97
+
98
+ def precondition_inputs(self, sample, sigma):
99
+ c_in = 1 / ((sigma**2 + self.config.sigma_data**2) ** 0.5)
100
+ scaled_sample = sample * c_in
101
+ return scaled_sample
102
+
103
+ def precondition_noise(self, sigma):
104
+ if not isinstance(sigma, torch.Tensor):
105
+ sigma = torch.tensor([sigma])
106
+
107
+ c_noise = 0.25 * torch.log(sigma)
108
+
109
+ return c_noise
110
+
111
+ def precondition_outputs(self, sample, model_output, sigma):
112
+ sigma_data = self.config.sigma_data
113
+ c_skip = sigma_data**2 / (sigma**2 + sigma_data**2)
114
+
115
+ if self.config.prediction_type == "epsilon":
116
+ c_out = sigma * sigma_data / (sigma**2 + sigma_data**2) ** 0.5
117
+ elif self.config.prediction_type == "v_prediction":
118
+ c_out = -sigma * sigma_data / (sigma**2 + sigma_data**2) ** 0.5
119
+ else:
120
+ raise ValueError(f"Prediction type {self.config.prediction_type} is not supported.")
121
+
122
+ denoised = c_skip * sample + c_out * model_output
123
+
124
+ return denoised
125
+
126
+ def scale_model_input(
127
+ self, sample: torch.FloatTensor, timestep: Union[float, torch.FloatTensor]
128
+ ) -> torch.FloatTensor:
129
+ """
130
+ Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
131
+ current timestep. Scales the denoising model input by `(sigma**2 + 1) ** 0.5` to match the Euler algorithm.
132
+
133
+ Args:
134
+ sample (`torch.FloatTensor`):
135
+ The input sample.
136
+ timestep (`int`, *optional*):
137
+ The current timestep in the diffusion chain.
138
+
139
+ Returns:
140
+ `torch.FloatTensor`:
141
+ A scaled input sample.
142
+ """
143
+ if self.step_index is None:
144
+ self._init_step_index(timestep)
145
+
146
+ sigma = self.sigmas[self.step_index]
147
+ sample = self.precondition_inputs(sample, sigma)
148
+
149
+ self.is_scale_input_called = True
150
+ return sample
151
+
152
+ def set_timesteps(self, num_inference_steps: int, device: Union[str, torch.device] = None):
153
+ """
154
+ Sets the discrete timesteps used for the diffusion chain (to be run before inference).
155
+
156
+ Args:
157
+ num_inference_steps (`int`):
158
+ The number of diffusion steps used when generating samples with a pre-trained model.
159
+ device (`str` or `torch.device`, *optional*):
160
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
161
+ """
162
+ self.num_inference_steps = num_inference_steps
163
+
164
+ ramp = torch.linspace(0, 1, self.num_inference_steps)
165
+
166
+ # ramp = np.linspace(0, 1, self.num_inference_steps)
167
+ sigmas = self._compute_sigmas(ramp)
168
+
169
+ # sigmas = torch.from_numpy(sigmas).to(dtype=torch.float32, device=device)
170
+ self.timesteps = self.precondition_noise(sigmas)
171
+
172
+ self.sigmas = torch.cat([sigmas, torch.zeros(1, device=sigmas.device)])
173
+ self._step_index = None
174
+ self._begin_index = None
175
+ self.sigmas = self.sigmas.to("cpu") # to avoid too much CPU/GPU communication
176
+
177
+ # Taken from https://github.com/crowsonkb/k-diffusion/blob/686dbad0f39640ea25c8a8c6a6e56bb40eacefa2/k_diffusion/sampling.py#L17
178
+ def _compute_sigmas(self, ramp, sigma_min=None, sigma_max=None) -> torch.FloatTensor:
179
+ """Constructs the noise schedule of Karras et al. (2022)."""
180
+
181
+ sigma_min = sigma_min or self.config.sigma_min
182
+ sigma_max = sigma_max or self.config.sigma_max
183
+
184
+ rho = self.config.rho
185
+ min_inv_rho = sigma_min ** (1 / rho)
186
+ max_inv_rho = sigma_max ** (1 / rho)
187
+ sigmas = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
188
+ # sigmas = (sigmas * (sigma_max - sigma_min)) / ((sigma_max - sigma_min) - sigmas).clamp(1e-8) # FIXED BY GIULIO
189
+ return sigmas
190
+
191
+ # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler.index_for_timestep
192
+ def index_for_timestep(self, timestep, schedule_timesteps=None):
193
+ if schedule_timesteps is None:
194
+ schedule_timesteps = self.timesteps
195
+
196
+ indices = (schedule_timesteps == timestep).nonzero()
197
+
198
+ # The sigma index that is taken for the **very** first `step`
199
+ # is always the second index (or the last index if there is only 1)
200
+ # This way we can ensure we don't accidentally skip a sigma in
201
+ # case we start in the middle of the denoising schedule (e.g. for image-to-image)
202
+ pos = 1 if len(indices) > 1 else 0
203
+
204
+ return indices[pos].item()
205
+
206
+ # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._init_step_index
207
+ def _init_step_index(self, timestep):
208
+ if self.begin_index is None:
209
+ if isinstance(timestep, torch.Tensor):
210
+ timestep = timestep.to(self.timesteps.device)
211
+ self._step_index = self.index_for_timestep(timestep)
212
+ else:
213
+ self._step_index = self._begin_index
214
+
215
+ def step(
216
+ self,
217
+ model_output: torch.FloatTensor,
218
+ timestep: Union[float, torch.FloatTensor],
219
+ sample: torch.FloatTensor,
220
+ s_churn: float = 0.0,
221
+ s_tmin: float = 0.0,
222
+ s_tmax: float = float("inf"),
223
+ s_noise: float = 1.0,
224
+ generator: Optional[torch.Generator] = None,
225
+ return_dict: bool = True,
226
+ ) -> Union[EDMEulerSchedulerOutput, Tuple]:
227
+ """
228
+ Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
229
+ process from the learned model outputs (most often the predicted noise).
230
+
231
+ Args:
232
+ model_output (`torch.FloatTensor`):
233
+ The direct output from learned diffusion model.
234
+ timestep (`float`):
235
+ The current discrete timestep in the diffusion chain.
236
+ sample (`torch.FloatTensor`):
237
+ A current instance of a sample created by the diffusion process.
238
+ s_churn (`float`):
239
+ s_tmin (`float`):
240
+ s_tmax (`float`):
241
+ s_noise (`float`, defaults to 1.0):
242
+ Scaling factor for noise added to the sample.
243
+ generator (`torch.Generator`, *optional*):
244
+ A random number generator.
245
+ return_dict (`bool`):
246
+ Whether or not to return a [`~schedulers.scheduling_euler_discrete.EDMEulerSchedulerOutput`] or
247
+ tuple.
248
+
249
+ Returns:
250
+ [`~schedulers.scheduling_euler_discrete.EDMEulerSchedulerOutput`] or `tuple`:
251
+ If return_dict is `True`, [`~schedulers.scheduling_euler_discrete.EDMEulerSchedulerOutput`] is
252
+ returned, otherwise a tuple is returned where the first element is the sample tensor.
253
+ """
254
+
255
+ if (
256
+ isinstance(timestep, int)
257
+ or isinstance(timestep, torch.IntTensor)
258
+ or isinstance(timestep, torch.LongTensor)
259
+ ):
260
+ raise ValueError(
261
+ (
262
+ "Passing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to"
263
+ " `EDMEulerScheduler.step()` is not supported. Make sure to pass"
264
+ " one of the `scheduler.timesteps` as a timestep."
265
+ ),
266
+ )
267
+
268
+ if not self.is_scale_input_called:
269
+ logger.warning(
270
+ "The `scale_model_input` function should be called before `step` to ensure correct denoising. "
271
+ "See `StableDiffusionPipeline` for a usage example."
272
+ )
273
+
274
+ if self.step_index is None:
275
+ self._init_step_index(timestep)
276
+
277
+ # Upcast to avoid precision issues when computing prev_sample
278
+ sample = sample.to(torch.float32)
279
+
280
+ sigma = self.sigmas[self.step_index]
281
+
282
+ gamma = min(s_churn / (len(self.sigmas) - 1), 2**0.5 - 1) if s_tmin <= sigma <= s_tmax else 0.0
283
+
284
+ noise = randn_tensor(
285
+ model_output.shape, dtype=model_output.dtype, device=model_output.device, generator=generator
286
+ )
287
+
288
+ eps = noise * s_noise
289
+ sigma_hat = sigma * (gamma + 1)
290
+
291
+ if gamma > 0:
292
+ sample = sample + eps * (sigma_hat**2 - sigma**2) ** 0.5
293
+
294
+ # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
295
+ pred_original_sample = self.precondition_outputs(sample, model_output, sigma_hat)
296
+
297
+ # 2. Convert to an ODE derivative
298
+ derivative = (sample - pred_original_sample) / sigma_hat
299
+
300
+ dt = self.sigmas[self.step_index + 1] - sigma_hat
301
+
302
+ prev_sample = sample + derivative * dt
303
+
304
+ # Cast sample back to model compatible dtype
305
+ prev_sample = prev_sample.to(model_output.dtype)
306
+
307
+ # upon completion increase step index by one
308
+ self._step_index += 1
309
+
310
+ if not return_dict:
311
+ return (prev_sample,)
312
+
313
+ return EDMEulerSchedulerOutput(prev_sample=prev_sample, pred_original_sample=pred_original_sample)
314
+
315
+ # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler.add_noise
316
+ def add_noise(
317
+ self,
318
+ original_samples: torch.FloatTensor,
319
+ noise: torch.FloatTensor,
320
+ timesteps: torch.FloatTensor,
321
+ ) -> torch.FloatTensor:
322
+ # Make sure sigmas and timesteps have the same device and dtype as original_samples
323
+ sigmas = self.sigmas.to(device=original_samples.device, dtype=original_samples.dtype)
324
+ if original_samples.device.type == "mps" and torch.is_floating_point(timesteps):
325
+ # mps does not support float64
326
+ schedule_timesteps = self.timesteps.to(original_samples.device, dtype=torch.float32)
327
+ timesteps = timesteps.to(original_samples.device, dtype=torch.float32)
328
+ else:
329
+ schedule_timesteps = self.timesteps.to(original_samples.device)
330
+ timesteps = timesteps.to(original_samples.device)
331
+
332
+ # self.begin_index is None when scheduler is used for training, or pipeline does not implement set_begin_index
333
+ if self.begin_index is None:
334
+ step_indices = [self.index_for_timestep(t, schedule_timesteps) for t in timesteps]
335
+ elif self.step_index is not None:
336
+ # add_noise is called after first denoising step (for inpainting)
337
+ step_indices = [self.step_index] * timesteps.shape[0]
338
+ else:
339
+ # add noise is called bevore first denoising step to create inital latent(img2img)
340
+ step_indices = [self.begin_index] * timesteps.shape[0]
341
+
342
+ sigma = sigmas[step_indices].flatten()
343
+ while len(sigma.shape) < len(original_samples.shape):
344
+ sigma = sigma.unsqueeze(-1)
345
+
346
+ mask = ((sigma - self.config.sigma_max).abs() < 1e-3).float() # changed by giulio
347
+
348
+ noisy_samples = (1 - mask) * (original_samples + noise * sigma) + mask * noise # changed by giulio
349
+ return noisy_samples
350
+
351
+ def __len__(self):
352
+ return self.config.num_train_timesteps