giulio98 commited on
Commit
a8f8e06
·
verified ·
1 Parent(s): cbd670c

Create scheduler/edm_euler_scheduler.py

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